Getting Resource id #3 Error in MySql

2020-03-24 06:22发布

问题:

I ran this code and I got a Resource id #3 error where it should have showed the full movies table.

mysql_connect("localhost", "root", "password") or die(mysql_error()); 
mysql_select_db("treehouse_movie_db") or die(mysql_error()); 
$data = mysql_query("SELECT * FROM movies") 
or die(mysql_error()); 
echo $data;

回答1:

This is not an error Your query is getting executed and you are getting appropriate resource from mysql_query() as it should be returned.

To get the response you have to use mysql_fetch_array() or mysql_fetch_assoc()

mysql_connect("localhost", "root", "password") or die(mysql_error()); 
mysql_select_db("treehouse_movie_db") or die(mysql_error()); 
$data = mysql_query("SELECT * FROM movies") 
or die(mysql_error()); 

while($row = mysql_fetch_assoc($data))
{
   print_r($row);
}

SUGGESTION: mysql_* are no longer maintained .Try switching to mysqli_* or PDO



回答2:

You're not getting an error, the MySQL API is just doing what you're asking it to: echoing the contents of $data, which is a MySQL query resource at this point. Extend the code to actually retrieve the results:

while($row = mysql_fetch_object($data))
    var_dump($row);

And you'll see the output.

Note that the mysql_* API is deprecated since PHP 5.5 by the way.