Jump to content

Chat script mysql_fetch_array(): supplied argument is not a valid MySQL result resource


cobusbo

Recommended Posts

Hi I'm currently having a problem with my chat script each time I'm trying to insert " or brackets etc... I get the error

 

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/u471530368/public_html/chat/page.php on line 201

 

 

Here is the lines at line 201


// check to see if a duplicate exists
$sql = "SELECT * FROM StringyChat WHERE StringyChat_ip=\"$ip\" AND StringyChat_message=\"$msg\" AND StringyChat_time>($post_time - 30 )";
$result = mysql_query($sql);
$myrow = mysql_fetch_array($result);

if($myrow["StringyChat_message"] == "") {    // Checks if record not matching in db
// Save the record
$sql = "INSERT INTO StringyChat (StringyChat_ip,StringyChat_name,StringyChat_message,StringyChat_time) VALUES (\"$ip\",\"$name\",\"$msg\",$post_time)";
$result = mysql_query($sql);
                
                 $theTo = $email_notification_to;
                 $theSubject = "New StringyChat post at ".$domain_installed;
                 $theMessage = "A new StringyChat post has been made.\n\n";
                 $theMessage .= $name . "\n";
                 $theMessage .= date("H:i - d/m/y", $post_time) . "\n";
                 $theMessage .= $message_emailable . "\n\n";
                 $theMessage .= "Visit ".$domain_installed." to view StringyChat and much more!";
                 $theHeaders = "From: StringyChat at ".$domain_installed." <".$email_notification_to.">\r\n";
                
                 mail($theTo,$theSubject,$theMessage,$theHeaders);

} else {
echo "<span style='color:#10ce59'>Duplicate post detected!</span><p>";
}
}
else {
echo "<span style='color:#10ce59'>You can't send blanks!</span><br><br>";
}

My full script is

 

<?php




define('TIMEZONE', 'Africa/Harare');
date_default_timezone_set(TIMEZONE);
?>
<html><br>
<b><u>Chat Beta:</u></b> 
<span style="color:#ff0000"><br>Errors may apply please send feedback with contact us regarding problems!</span>
<br><a href="page.php">Reload</a>
</html>
<?
// database connection info
$conn = mysql_connect('*******','********','*****') or trigger_error("SQL", E_USER_ERROR);
$db = mysql_select_db('*******',$conn) or trigger_error("SQL", E_USER_ERROR);




// find out how many rows are in the table 
$sql = "SELECT COUNT(*) FROM StringyChat";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];


// number of rows to show per page
$rowsperpage = 20;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);


// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
   // cast var as int
   $currentpage = (int) $_GET['currentpage'];
} else {
   // default page num
   $currentpage = 1;
} // end if


// if current page is greater than total pages...
if ($currentpage > $totalpages) {
   // set current page to last page
   $currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
   // set current page to first page
   $currentpage = 1;
} // end if


// the offset of the list, based on current page 
$offset = ($currentpage - 1) * $rowsperpage;








    /*
     * StringyChat
     *
* Please refer to readme.txt supplied with the StringyChat distribution for information on
* installing and configuring. 
*
     */










define('TIMEZONE', 'Africa/Harare');
date_default_timezone_set(TIMEZONE);






    include("chat_code_header.php");


    $result = mysql_query("SELECT * FROM ".$ConfigTable, $db); 
    $myrow = mysql_fetch_array($result); 


    $domain_installed = $myrow["domain_installed"]; // The domain StringyChat is installed on
$install_url = $myrow["install_url"]; // URL to install dir of StringyChat
    $name_size = $myrow["name_size"]; // Maximum size of the name
    $message_size = $myrow["message_size"]; // Maximum message size. Do not exceed 250 as this is the database limit.
    $line_length = $myrow["line_length"]; // Maximum length of words in a line. Anything above this value will be split.
    $ShowPostNum = $myrow["show_posts"]; // The number of historic posts to load and display.
    $email_notification = $myrow["email_notification"]; // Send email to administrator when new posts are made. 0 = No, 1 = Yes
$email_notification_to = $myrow["email_notification_to"]; // The email address to send notifications to


    
if ($_SERVER['REQUEST_METHOD'] == "POST" && !empty($_POST['StringyChat_name'])) 
    { 
    $StringyChat_name = $_POST['StringyChat_name'];
    $StringyChat_message = $_POST['StringyChat_message'];
    }


?>


<div id="StringyChat">


<?
    // Check if visitor's IP is banned.  If so, do not display the form,
    // show a banned IP message instead.


$name = $_SERVER["HTTP_X_MXIT_NICK"];
if(!isset($name))
{
$name = "SYSOP";
}








    $ip = $_SERVER["REMOTE_ADDR"];
    $sql = "SELECT * FROM StringyChat_IPBan WHERE ip=\"$ip\"";
    $result = mysql_query($sql);
    $myrow = mysql_fetch_array($result);
    if($myrow["ip"] == "") { // Checks if IP not found in banned list








?>
<html><form name="StringyChat_form" method="POST" action="<? echo $_SERVER['REQUEST_URI']; ?>">
      <input type="hidden" name="StringyChat_name" class="StringyChatFrm" value="<?php echo $name ?>" size="20">
      <textarea name="StringyChat_message" class="StringyChatFrm" cols="20" rows="1"></textarea>
      <br>
      <input name="StringyChat_submit" class="StringyChatFrm" type="submit" value="Post Message">
    </form>
</html>


<?


    } else {
      echo "<span style='color:#10ce59'><u>Dear User, you have been banned from the Chat due to not following the rules. You will need to come back regularly to see if you were unbanned. Until then, goodbye!</u></span>";
    }
    
    // Should we try to create a post?
    if (isset($StringyChat_name) && isset($StringyChat_message)) {


        // Remove whitespaces and slashes.
        $name = trim(stripslashes($StringyChat_name));
        $message = trim(stripslashes($StringyChat_message));


        
            // Check name and message have been entered.
            if (strlen($name) > 0 && strlen($message) > 0) {
                
                // Limit the size of the fields as per variable defnitions.
                if (strlen($name) > $name_size) {
                    $name = substr($name, 0, $name_size);
                }
                if (strlen($message) > $message_size) {
                    $message = substr($message, 0, $message_size);
                }
                
                // Remove new lines from name.
                $name = str_replace("\n", " ", $name);
                
// Stripping out \r's so email formattnig appears correctly.
$message = str_replace("\r", "", $message);


// Create an email-friendly version of the message.
$message_emailable = str_replace("<br>", "\n", $message);
$result_wordswap = mysql_query("SELECT * FROM ".$WordBanTable,$db);
                while ($myrow_wordswap = mysql_fetch_array($result_wordswap)) {
             $the_word = $myrow_wordswap["word"];
                  $message_emailable = ereg_replace($the_word, "!*#$%",$message_emailable);
                }


                // Replace the new lines with encoded line breaks for HTML (thanks milahu).
                $message = str_replace("\n", "c#lb", $message);


                // Use HTML encoding on ame and message so database doesn't misinterpret data.
           $name = htmlentities($name);
                $message = htmlentities($message, ENT_COMPAT);


                
                
                // IP address of submitter and time of post.
$ip = $_SERVER["REMOTE_ADDR"];
$name = $_SERVER["HTTP_X_MXIT_NICK"];
$msg = $_POST['StringyChat_message'];
$post_time = date("U");
$mxitid = $_SERVER["HTTP_X_MXIT_LOGIN"];






if(!isset($mxitid))
{
$mxitid = "DEFAULT";


}
if(!isset($name))
{
$name = "SYSOP";
}








                // check to see if a duplicate exists
                $sql = "SELECT * FROM StringyChat WHERE StringyChat_ip=\"$ip\" AND StringyChat_message=\"$msg\" AND StringyChat_time>($post_time - 30 )";
                $result = mysql_query($sql);
                $myrow = mysql_fetch_array($result);


                if($myrow["StringyChat_message"] == "") { // Checks if record not matching in db
                  // Save the record
                  $sql = "INSERT INTO StringyChat (StringyChat_ip,StringyChat_name,StringyChat_message,StringyChat_time) VALUES (\"$ip\",\"$name\",\"$msg\",$post_time)";
                  $result = mysql_query($sql);


 $theTo = $email_notification_to;
 $theSubject = "New StringyChat post at ".$domain_installed;
 $theMessage = "A new StringyChat post has been made.\n\n";
 $theMessage .= $name . "\n";
 $theMessage .= date("H:i - d/m/y", $post_time) . "\n";
 $theMessage .= $message_emailable . "\n\n";
   $theMessage .= "Visit ".$domain_installed." to view StringyChat and much more!";
 $theHeaders = "From: StringyChat at ".$domain_installed." <".$email_notification_to.">\r\n";


 mail($theTo,$theSubject,$theMessage,$theHeaders);


                } else {
                  echo "<span style='color:#10ce59'>Duplicate post detected!</span><p>";
                }                
            }
            else {
                echo "<span style='color:#10ce59'>You can't send blanks!</span><br><br>";
            }


      unset($_POST["StringyChat_name"]);
      unset($_POST["StringyChat_message"]);
      unset($StringyChat_ip);
      unset($StringyChat_name);
      unset($StringyChat_message);
      unset($StringyChat_time);
      unset($mxit_id);


    }
    
// get the info from the db 
$sql = "SELECT StringyChat_time, StringyChat_name, StringyChat_message FROM StringyChat ORDER BY id DESC LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);






function filterBadWords($str)
{




    $result1 = mysql_query("SELECT word FROM StringyChat_WordBan") or die(mysql_error()); 
    $replacements = ":-x";
    
    while($row = mysql_fetch_assoc($result1))
    {
          $str = eregi_replace($row['word'], str_repeat(':-x', strlen($row['word'])), $str);
    }  
    
    return $str;
}






// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) 
//while (($pmsg = $list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])
 {
   // echo data
   //echo ($pmsg = ($list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])
$admin = array('cobusbo','Admin+TT');






if (in_array($list['StringyChat_name'], $admin))
{
   print '<span style="color:#828282">' . '(' . date( 'D H:i:s', $list['StringyChat_time'] )  . ') ' . '</span>' . '<span style="color:red">' .  '<b>' . $list['StringyChat_name'] . '</b>' . ' : ' . filterBadWords($list['StringyChat_message']) . '</span>' . '<br />' . '<p>';
}
else
{
   print '<span style="color:#828282">' . '(' . date( 'D H:i:s', $list['StringyChat_time'] )  . ') ' . '</span>' .  '<b>' . $list['StringyChat_name'] . '</b>' . ' : ' . filterBadWords($list['StringyChat_message']) . '<br />' . '<p>';
}












}












    // Load up the last few posts.  The number to load is defined by the "ShowPostNum" variable.
    $result = mysql_query("SELECT * FROM ".$dbTable." ORDER BY StringyChat_time DESC LIMIT " . $ShowPostNum,$db);


    include("sort_widths.php");


    while ($myrow = mysql_fetch_array($result)) {
      $msg = $myrow["StringyChat_message"];


 // Convert the encoded line break into an actual <br> tag (thanks milahu)
      $msg = str_replace("c#lb", "<br>", $msg);


      // Convert the encoded image tag into a html tag
      $msg = eregi_replace("im#([a-z]{3})", "<img src=\"http://".$install_url."images/\\1.gif\" alt=\"emoticon\">",$msg);


 // split the lines
      $msg = htmlwrap($msg, $line_length);


      $result_wordswap = mysql_query("SELECT * FROM ".$WordBanTable,$db);
      while ($myrow_wordswap = mysql_fetch_array($result_wordswap)) {
   $the_word = $myrow_wordswap["word"];
        $msg = ereg_replace($the_word, ":-x",$msg);
      }


   
    }
   ?>     
<?


















// end while


/******  build the pagination links ******/
// range of num links to show
$range = 3;


// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if 


// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo " [<b>$x</b>] ";
      // if not current page...
      } else {
         // make it a link
         echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
      } // end else
   } // end if 
} // end for


// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) {
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
   // echo forward link for lastpage
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/


?><br>
    <html>  <span style="color:grey"><i>Type Your Message NOW!</i></span>
<p><a href="page.php">Reload</a> | <a href="http://tt.2fh.co">Home</a><br></html>

Any help please... If I send normal messages I don't get any errors...

 

Link to comment
Share on other sites

Your query is failing and, more importantly, is not secure - you are open to SQL injection. You need to change to mysqli_ or PDO for your DB transactions and use Prepared Statements. That will fix your issue and resolve the SQL Injection problem.

 

I prefer PDO. here is a cursory tutorial that will get you going in the right direction: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059

Edited by Psycho
Link to comment
Share on other sites

Your query is failing and, more importantly, is not secure - you are open to SQL injection. You need to change to mysqli_ or PDO for your DB transactions and use Prepared Statements. That will fix your issue and resolve the SQL Injection problem.

 

I prefer PDO. here is a cursory tutorial that will get you going in the right direction: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059

This will mean I will have to change the script from scratch...

Isn't there a way to fix it otherwise since its a very old script running on an old version of php 5.4.2 I think...

Link to comment
Share on other sites

This will mean I will have to change the script from scratch...

Isn't there a way to fix it otherwise since its a very old script running on an old version of php 5.4.2 I think...

 

Why would it have to be rewritten from scratch? All you need to do is change the code that interact with the DB. It is not that much different from what you already have. Now, I could show you how to write more deprecated code to work around the problem. But, that doesn't make sense. If you don't understand the current problem with the deprecated code, why would you want to invest time into learning more about how to write better deprecated code? You could invest that time into learning how to do it correctly. Did you even read the tutorial I provided above?

 

This is a quick rewrite of some of that code. I didn't test it so there might be a few minor issues

 

//Connect to the DB
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
 
// check to see if a duplicate exists
$sql = "SELECT StringyChat_message FROM StringyChat
        WHERE StringyChat_ip=\"$ip\" AND StringyChat_message=\"$msg\"
          AND StringyChat_time>($post_time - 30 )";
$sth = $dbh->query($sql);
//$result = mysql_query($sql);
$myrow = $sth->fetch(PDO::FETCH_ASSOC);
 
// Checks if record not matching in db
if($myrow['StringyChat_message'] == "")
{    
    //Create prepared statement
    $sql = "INSERT INTO StringyChat
                (StringyChat_ip, StringyChat_name, StringyChat_message, StringyChat_time)
            VALUES
                (:ip, :name, :msg, :post_time)";
    $sth = $dbh->prepare($sql);
 
    //The data we want to insert
    $data = array( 'ip' => $ip, 'name' => $name, 'msg' => $msg, 'post_time' => $post_time);
 
    //Run the query
    $result = $sth->execute($data);
 
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.