mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc… expects parameter 1 to be resource

后端 未结 30 2690
鱼传尺愫
鱼传尺愫 2020-11-21 06:25

I am trying to select data from a MySQL table, but I get one of the following error messages:

mysql_fetch_array() expects parameter 1 to be resource,

30条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 07:13

    This error message is displayed when you have an error in your query which caused it to fail. It will manifest itself when using:

    • mysql_fetch_array/mysqli_fetch_array()
    • mysql_fetch_assoc()/mysqli_fetch_assoc()
    • mysql_num_rows()/mysqli_num_rows()

    Note: This error does not appear if no rows are affected by your query. Only a query with an invalid syntax will generate this error.

    Troubleshooting Steps

    • Make sure you have your development server configured to display all errors. You can do this by placing this at the top of your files or in your config file: error_reporting(-1);. If you have any syntax errors this will point them out to you.

    • Use mysql_error(). mysql_error() will report any errors MySQL encountered while performing your query.

      Sample usage:

      mysql_connect($host, $username, $password) or die("cannot connect"); 
      mysql_select_db($db_name) or die("cannot select DB");
      
      $sql = "SELECT * FROM table_name";
      $result = mysql_query($sql);
      
      if (false === $result) {
          echo mysql_error();
      }
      
    • Run your query from the MySQL command line or a tool like phpMyAdmin. If you have a syntax error in your query this will tell you what it is.

    • Make sure your quotes are correct. A missing quote around the query or a value can cause a query to fail.

    • Make sure you are escaping your values. Quotes in your query can cause a query to fail (and also leave you open to SQL injections). Use mysql_real_escape_string() to escape your input.

    • Make sure you are not mixing mysqli_* and mysql_* functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick with mysqli_*. See below for why.)

    Other tips

    mysql_* functions should not be used for new code. They are no longer maintained and the community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is good PDO tutorial.

提交回复
热议问题