简体   繁体   中英

php/sql error - mysql_fetch_assoc()

I'm receiving the following error:

mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource..

and I can't figure out what is going on. Here is my code. I did create a database with a table named notes. Also, the database connection is working correctly. Any idea on what is going on?

$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");
mysql_fetch_assoc($query)

Thanks

  1. var_dump($query);
  2. echo mysql_error();

Did mysql_query fail and return FALSE ? As the documentation explains:

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

FALSE would not be a valid resource.

On the PHP page, it gives you a perfect example of how to use it and do error checking...

$conn = mysql_connect("localhost", "mysql_user", "mysql_password");

if (!$conn) {
    echo "Unable to connect to DB: " . mysql_error();
    exit;
}

if (!mysql_select_db("mydbname")) {
    echo "Unable to select mydbname: " . mysql_error();
    exit;
}

$sql = "SELECT id as userid, fullname, userstatus 
        FROM   sometable
        WHERE  userstatus = 1";

$result = mysql_query($sql);

if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
}

if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}

// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
//       then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}

How about you go and implement the entire way making sure rows are returned, and its a valid resource, and if result is truthy?

You should always debug and never assume something executed rightfully.

In the future please read through the entire page of the function on php.net, in this case it's http://php.net/manual/en/function.mysql-fetch-assoc.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM