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
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'];
}
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.