I'm trying to get data from a MySQL table, but one of these errors comes up:

mysql_fetch_array () expects parameter 1, be resource, boolean given

or

mysqli_fetch_array () expects parameter 1 to be mysqli_result, boolean given

Here is my code:

$username = $_POST['username']; $password = $_POST['password']; $result = mysql_query("SELECT * FROM Users WHERE UserName LIKE $username"); while($row = mysql_fetch_array($result)) { echo $row['FirstName']; } 

The original question .

3 answers 3

How to avoid such an error

This error is secondary. And in a properly designed application, it should not arise in principle.

It only signals that the previous function that executed the SQL query failed, but does not carry any information about the cause of the failure.

To avoid such errors in the code, it is necessary to check the result of the same previous function that performed the SQL query. But this should be done with the mind, and not in the way that non-specialists advise, for decades rewriting the same code from each other, not understanding its meaning and not interfering with the results of its work ( very deplorable ) in practice.

When calling the mysql_query() function, you should always check the result of its work. And if the function returned not a correct resource, but emptiness, then it is necessary, first, to receive an error message from mysql, and secondly, to translate it into a PHP error (this is a fundamental point that novice PHP users do not understand completely). And thirdly, it is very useful to add the request itself to the error message.

The mysql_error() function is responsible for the first, trigger_error() for the second, and for the third, you must always assign the request to a variable first. Thus, any mysql_query() call should look like this:

 $sql = "SELECT ..."; $res = mysql_query($sql) or trigger_error(mysql_error()." in ". $sql); 

Thus, when an error occurs in the execution of the request, the PHP user will be immediately informed in the same way as about any other errors occurring in the script. And before the error "expects parameter" it no longer comes.

In principle, even better than trigger_error (), it would throw an exception. But since

  • throw new Exception() cannot be substituted so pretty via or in the same line;
  • PHP beginner users are very poorly aware of the exclusion mechanism and immediately begin to use it incorrectly;
  • the mysql extension has already lost all meaning, and the remaining two, mysqli and PDO are able to translate database errors into exceptions automatically ,

suggesting exceptions for mysql_query() is somehow silly. But in any case, no matter how the error is handled, it must follow two immutable rules:

  1. No echo and die() !!! Database errors should always be translated to PHP errors and output where all others are output. If the site prohibits the display of errors in the browser, then database errors should not be an exception to this rule.
  2. The error message must contain the name of the file and the line in which the error occurred, and, if possible, a trace of the calls.

How to fix the error.

You must read the error message.

It sounds commonplace, but surprisingly, none of the laypersons who give advice never mentions it! While reading the text of the error helps a hundred times better than shamanic gestures like "recount all quotes":

First, mysql will immediately tell you what the essence of the error is . If there is no table in the database to which we are accessing, or the entire server has completely dropped, then it is useless to recalculate the quotes.
Secondly, if the error is still in the syntax, then mysql will accurately indicate the place where to look for it - it will quote a piece of query that starts right after the error.

Get rid of syntax errors caused by data once and for all.

If the problem is still in syntax, and at the same time caused by the data sent to the request, then the Foolish Idea itself will "screen your values ​​with mysql_real_escape_string() ". And even more stupid will use this feature to protect against SQL injection. It is not intended for this.

In order to permanently get rid of any problems associated with the variables passed to the query, you must stop inserting them directly into the query string. And to do this only through an intermediary , called "placeholder" .

A driver for working with a database through placeholders can be written on the basis of any API - be it mysql, mysqli or PDO. But since, firstly, for this you need to have special knowledge, and secondly, beginner PHP users are terribly afraid of any ready-made libraries, preferring to use only built-in language tools, they have only one choice left - PDO.

Mysqli

To translate database errors into PHP errors, mysqli does not need to check the result of each function. Instead, just write a line like this before the connection:

 mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); 

and then all database errors will raise exceptions, which by default become fatal PHP errors and in this form will be available to the programmer.

    Where does the error come from

    This error occurs if the request cannot be executed. Functions that can lead to it:

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

    If the request is OK, and just the result of its execution is empty, the error does not occur. Only incorrect SQL syntax results in an error.

    How to find the source of the error

    • Make sure that the server where you are developing is enabled to display all errors. You can enable it from PHP by executing error_reporting(-1); (you can place this code in the configuration file of your site, for example). If, when trying to execute a query, errors in the syntax are found, they will be displayed.

    • Use mysql_error() . This function will return a string with the error text, if one has occurred during the execution of the last query.

      For example:

       mysql_connect($host, $username, $password) or die("Ошибка подключения"); mysql_select_db($db_name) or die("Ошибка выбора БД"); $sql = "SELECT * FROM table_name"; $result = mysql_query($sql); if ($result === false) { echo mysql_error(); } 
    • Run your query on the MySQL command line or from a tool like phpMyAdmin . If there is a syntax error in the request, it will be displayed.

    • Ensure that the query is correctly placed quotes. This is a common cause of syntax errors.

    • Make sure you screen your values. If there is a quotation mark in the string, this can lead to an error (and also make your code vulnerable to SQL injection). Use mysql_real_escape_string() for this.

    • Make sure you do not use the mysqli_* and mysql_* functions at the same time. Their use cannot be mixed. (If you do not know what to choose, give preference to mysqli_* .)

    Tips

    Do not use the mysql_* function in new code. PHP developers no longer support or develop them, they are marked as obsolete, and will be removed in future versions. Familiarize yourself with the concept of the prepared statement and go on using PDO (PHP Data Objects) or MySQLi (MySQL improved). This will save you from problems with shielding values ​​and save from SQL injections.

    Both MySQLi and PDO support a mode in which exceptions are thrown when errors occur. In the new code, this approach should be used, because it helps to handle errors in one place, rather than smear checks across the code, and allows error handling not to depend on external conditions (on the configuration).

    Comparison of PDO and MySQLi features . In short, PDO is a common layer above the database, which makes it relatively easy to switch the DBMS; MySQLi gives you access to some additional features of MySQL DBMS.

    Predominantly translation of the answer .

       $username = $_POST['username']; $password = $_POST['password']; if ($result = mysql_query("SELECT * FROM Users WHERE UserName LIKE $username") and mysql_num_rows($result)){ while($row = mysql_fetch_assoc($result)) { echo $row['FirstName']; } }else{ if (!mysql_num_rows($result)){ echo "empty result"; }else{ echo mysql_error(); } } 
      • five
        Please try to write more detailed answers. I am sure the author of the question would be grateful for your expert commentary on the code above. - Nicolas Chabanovsky

      Protected by ReinRaus member on Sep 18 '15 at 10:42 .

      Thank you for your interest in this issue. Since he collected a large number of low-quality and spam responses, which had to be deleted, now it’s necessary to have 10 reputation points on the site (the bonus for account association is not counted ).

      Maybe you want to answer one of the unanswered questions ?