I'm looking for the best way to check and see if any results were returned in a query. I feel like I write this part of code a lot and sometimes I get errors, and sometimes I don't.
For example, I run this query to check if a username exists before inserting a new one into the database.
$result = mysql_query("SELECT * FROM ...");
Then I want to check and see if any results were returned. Here is one way I do it:
if (!$result) { PERFORM ACTION }
If the first way doesn't work, then sometimes this will:
if (mysql_num_rows($result)==0) { PERFORM ACTION }
Then I even saw that I could do it this way the other day:
list($total) = mysql_fetch_row($result); if ($total==0) { PERFORM ACTION }
What is the best way to do this?
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.
PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.
Return Values ¶ For successful queries which produce a result set, such as SELECT, SHOW, DESCRIBE or EXPLAIN , mysqli_query() will return a mysqli_result object. For other successful queries, mysqli_query() will return true .
if (mysql_num_rows($result)==0) { PERFORM ACTION }
For PHP 5 and 7 and above use mysqli:
if (mysqli_num_rows($result)==0) { PERFORM ACTION }
One way to do it is to check what mysql_num_rows
returns. A minimal complete example would be the following:
if ($result = mysql_query($sql) && mysql_num_rows($result) > 0) { // there are results in $result } else { // no results }
But it's recommended that you check the return value of mysql_query
and handle it properly in the case it's false
(which would be caused by an error); probably by also calling mysql_error
and logging the error somewhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With