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, boolean given
or
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
or
Call to a member function fetch_array() on boolean / non-object
This 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 same applies to code like
$result = mysqli_query($mysqli, 'SELECT ...');
// mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
while( $row=mysqli_fetch_array($result) ) {
...
and
$result = $mysqli->query($mysqli, 'SELECT ...');
// Call to a member function fetch_assoc() on a non-object
while( $row=$result->fetch_assoc($result) ) {
...
and
$result = $pdo->query('SELECT ...', PDO::FETCH_ASSOC);
// Invalid argument supplied for foreach()
foreach( $result as $row ) {
...
and
$stmt = $mysqli->prepare('SELECT ...');
// Call to a member function bind_param() on a non-object
$stmt->bind_param(...);
and
$stmt = $pdo->prepare('SELECT ...');
// Call to a member function bindParam() on a non-object
$stmt->bindParam(...);
Include a connection string variable before the MySQL query. For example,
$connt
in this code:Any time you get the...
...it is likely because there is an issue with your query. The
prepare()
orquery()
might returnFALSE
(a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening
<?php
tag:If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at
/var/log/apache2/error.log
. If you're examining error logs in a Linux environment you can usetail -f /path/to/log
in a console window to see errors as they occur in real-time....or as you make them.Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:
The error is generic and not very helpful to you in solving what is going on.
With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the
prepare()
statement for truthiness and if it is good you can proceed on to binding and executing.If something is wrong you can spit out an error message which takes you directly to the issue. In this case there is no
foo
column in the table, solving the problem is trivial.If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.
A query may fail for various reasons in which case both the mysql_* and the mysqli extension will return
false
from their respective query functions/methods. You need to test for that error condition and handle it accordingly.mysql_* extension:
Check
$result
before passing it tomysql_fetch_array
. You'll find that it'sfalse
because the query failed. See themysql_query
documentation for possible return values and suggestions for how to deal with them.mysqli extension
procedural style:
oo-style:
using a prepared statement:
These examples only illustrate what should be done (error handling), not how to do it. Production code shouldn't use
or die
when outputting HTML, else it will (at the very least) generate invalid HTML. Also, database error messages shouldn't be displayed to non-admin users, as it discloses too much information.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:
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_*
andmysql_*
functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick withmysqli_*
. 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.This query should work:
The problem is single quotes, thus your query fails and returns FALSE and your WHILE loop can't execute. Using % allows you to match any results containing your string (such as SomeText-$username-SomeText).
This is simply an answer to your question, you should implement stuff mentioned in the other posts: error handling, use escape strings (users can type anything into the field, and you MUST make sure it is not arbitrary code), use PDO instead mysql_connect which is now depricated.
You can also check wether
$result
is failing like so, before executing the fetch array