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(...);
There might be two reasons:
Have you opened the connection to the database prior to calling mysql_query function? I don't see that in your code. Use mysql_connect before making the query. See
php.net/manual/en/function.mysql-connect.php
The variable $username is used inside a single quote string, so its value will not be evaluated inside the query. The query will definitely fail.
Thirdly, the structure of query is prone to SQL injection. You may use prepared statements to avoid this security threat.
Try this code it work fine
assign the post variable to the variable
Put quotes around
$username
. String values, as opposed to numeric values, must be enclosed in quotes.Also, there is no point in using the
LIKE
condition if you're not using wildcards: if you need an exact match use=
instead ofLIKE
.Error occurred here was due to the use of single quotes (
'
). You can put your query like this:It's using
mysql_real_escape_string
for prevention of SQL injection. Though we should use MySQLi or PDO_MYSQL extension for upgraded version of PHP (PHP 5.5.0 and later), but for older versionsmysql_real_escape_string
will do the trick.First, check your connection to the database. Is it connected successfully or not?
If it's done, then after that I have written this code, and it works well:
As scompt.com explained, the query might fail. Use this code the get the error of the query or the correct result:
See the documentation for
mysql_query()
for further information.The actual error was the single quotes so that the variable
$username
was not parsed. But you should really usemysql_real_escape_string($username)
to avoid SQL injections.