Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if mysql_query returned any results?

Tags:

php

mysql

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?

like image 592
timroman Avatar asked Nov 26 '10 15:11

timroman


People also ask

What does mysql_query return?

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.

How check query result is empty in PHP?

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.

What is the return type of Mysqli_query?

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 .


2 Answers

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 } 
like image 138
benhowdle89 Avatar answered Oct 18 '22 20:10

benhowdle89


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.

like image 26
Shoe Avatar answered Oct 18 '22 19:10

Shoe