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

后端 未结 30 3349
鱼传尺愫
鱼传尺愫 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:08

    Traditionally PHP has been tolerant to bad practice and failures in code, which makes debugging quite hard. The problem in this specific case is that both mysqli and PDO by default don't tell you, when a query failed and just return FALSE. (I will not talk about the depricated mysql extention. The support for prepared statements is reason anough to switch either to PDO or mysqli.) But you can change the default behavior of PHP to always throw exceptions when a query fails.

    For PDO: Use $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    error_reporting(E_ALL);
    
    $pdo = new PDO("mysql:host=localhost;dbname=test", "test","");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $result = $pdo->query('select emal from users');
    $data = $result->fetchAll();
    

    This will show you the following:

    Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\pdo.php on line 8

    PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\pdo.php on line 8

    As you see, it tells you exactly, what is wrong with the query, and where to fix it in your code.

    Without $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); you will get

    Fatal error: Call to a member function fetchAll() on boolean in E:\htdocs\test\mysql_errors\pdo.php on line 9

    For mysqli: Use mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    error_reporting(E_ALL);
    
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $mysqli = new mysqli('localhost', 'test', '', 'test');
    
    $result = $mysqli->query('select emal from users');
    $data = $result->fetch_all();
    

    You will get

    Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\mysqli.php on line 8

    mysqli_sql_exception: Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\mysqli.php on line 8

    Without mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); you only get

    Fatal error: Call to a member function fetch_all() on boolean in E:\htdocs\test\mysql_errors\mysqli.php on line 10

    Of course, you could manually check the MySQL errors. But I would go crazy if I had to do that every time I made a typo - or worse - every time I want to query the database.

提交回复
热议问题