Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the proper way to check if mysql_query() returned any results?

Tags:

php

mysql

I tried what seemed like the most intuitive approach

$query = "SELECT * FROM members 
          WHERE username = '$_CLEAN[username]'
          AND password = '$_CLEAN[password]'";
$result = mysql_query($query);

if ($result)
{ ... 

but that didn't work because mysql_query returns a true value even if 0 rows are returned.

I basically want to perform the logic in that condition only if a row is returned.

like image 842
Ryan Avatar asked Jul 24 '09 22:07

Ryan


People also ask

What will be the return value of mysql_query () function on error?

mysql_query() returns TRUE (non-zero) or FALSE to indicate whether or not the query succeeded. A return value of TRUE means that the query was legal and could be executed by the server. It does not indicate anything about the number of rows affected or returned.

What is the use of mysql_query () function?

mysql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if mysql_connect() was called with no arguments, and use it.

How do I check if SQL query returns nothing PHP?

The is_null() function checks whether a variable is NULL or not. This function returns true (1) if the variable is NULL, otherwise it returns false/nothing.


2 Answers

Use mysql_num_rows:

 if (mysql_num_rows($result)) {
    //do stuff
 }
like image 53
thedz Avatar answered Sep 19 '22 17:09

thedz


If you're checking for exactly one row:

if ($Row = mysql_fetch_object($result)) {
    // do stuff
}

You can use mysql_fetch_array() instead, or whatever, but the principle is the same. If you're doing expecting 1 or more rows:

while ($Row = mysql_fetch_object($result)) {
    // do stuff
}

This will loop until it runs out of rows, at which point it'll continue on.

like image 42
dirtside Avatar answered Sep 21 '22 17:09

dirtside