1

How do I fix the "Mysql_fetch_array supplied argument is not a valid MYSQL result" error?

This is the code that had the error:

<?php
    require "connect.php";
    $query = mysql_query("SELECT author, date 
                            FROM articles 
                           WHERE id = ' . $id . '") or die(mysql_error());
    $runrows = mysql_fetch_array('$query');

     $author = $runrows['author'];
     $date = $runrows['date'];        
?>
5

4 Answers 4

3
  $query = mysql_query("SELECT author, date FROM articles WHERE id = ' . $id . '") or die(mysql_error());
  $runrows = mysql_fetch_array($query);

There should be no quotes for $query. Its a variable, not a string.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Right, in fact $query is a resource, therefore it makes no sense to make it part of an expression or interpolation.
1
$runrows = mysql_fetch_array('$query');

Should be

$runrows = mysql_fetch_array($query);

or

$runrows = mysql_fetch_array("$query");

Using '$variable' just prints out $variable as text. You want to use the value of the variable.

SQL Injection is when you use that $id variable from user interaction.

E.g. you have the following URL:

http://example.com/articles.php?id=1

If you just add the id variable to your query people can inject code in the variable.

http://en.wikipedia.org/wiki/SQL_injection

To prevent this you can simply do: $id = mysql_real_escape_string($id);

Or use prepared statements if it is supported.

http://en.wikipedia.org/wiki/Prepared_statements#Parameterized_statements

Comments

0

Remove the dots and use something like this in the third line

$query = mysql_query("SELECT author, date FROM articles WHERE id = '$id'") or die(mysql_error());

Comments

0

This has happened to me when I had not closed the connection using mysql_close($conn). I guess the socket between from the db was still open, and next time when i again connected to the same db, this particular error came. There were no other issues. Once I explicitly closed the connection and then again restarted the connection, this issue was resolved. Hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.