PHP Error - MYSQL Function

by 6 replies
7
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource

Having some trouble... can't figure it out what is wrong.

<?php
if(isset($_POST['post'])){
if($_POST['title'] || $_POST['text'] || $_POST['text'] > 24){
$title = clean($_POST['title']);
$text = clean($_POST['text']);
$showselect = $_POST['show'];
$sql = "SELECT `id` FROM `show` WHERE `show_title` = '$showselect'";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query)){
$sql = "INSERT INTO `blog` (show_id, title, content) VALUES('".$row['id']."', '$title', '$text')";
$query = mysql_query($sql);
if($query == TRUE)
echo "
Your blog post has been successfully added to the database.
";
else
echo "ERROR";
}
}else
echo "
All fields are required and the text must be <b>over</b> 24.
";
}
?>
#programming #error #function #mysql #php
  • You'll get better error reporting if you do this:
    PHP Code:
    $query mysql_query($sql) or die(mysql_error()); 
    instead of your current mysql_query. This will allow MySQL to report what is wrong with your SQL query instead of relying on PHP's error reporting.
  • As an additional note (this may even be the source of your problem), you should be escaping your $_POST['show'] since it comes from an unreliable source (a form). It could have double quotes in it, which would mess up your SQL, or worse have double quotes followed by more SQL code, which could cause SQL injection (a form of hacking). You should always escape user input used in SQL queries like so:

    PHP Code:
    $showselect mysql_real_escape($_POST['show']); 
    This will escape this data based on the exact current encoding of the currently connected database.
  • You're redefining $query inside the loop. You might want to rename it.
  • $sql = "SELECT `id` FROM `show` WHERE `show_title` = '$showselect'";

    Should be:

    $sql = "SELECT * FROM show WHERE show_title='$showselect'";

    ... I think you want ALL the results where show_title = your variable..

    Also.. change this part...

    VALUES('".$row['id']."', '$title', '$text')";

    to

    VALUES('$row[id]', '$title', '$text')";

    ... you dont need to use the . to join... just remove the quotes...
  • KirkMcD is correct, there are other causes for this error as well:

    Sometimes you will get this error if your query returns zero rows. You could use a statement like this to determine if you have a result:

    if (mysql_num_rows($query) > 0)
    {
    //Put the code here
    }
  • Issue resolved.. Thanks for your help NerdGary. And other too!!!

Next Topics on Trending Feed