Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP & MySQL, what's returned when the query yields no rows?

Tags:

php

mysql

I'm a little confused about something in the PHP interface to MySQL. The documentation for mysql_query (used to execute commands and queries) says this for return values:

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.

Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query.

I understand that I can call mysql_num_rows to get a count of the returned rows from a query assuming I did a command in the {SELECT, SHOW, DESCRIBE, EXPLAIN} set.

Aside from that though... what happens if a query in that set executes successfully (database wise) but returns no result rows? Does mysql_query return true or false in that case (i.e. is this a failure condition)? What's the best way to check for the "no results" possibility of a successful query using this interface?

like image 259
John Humphreys Avatar asked Oct 10 '11 18:10

John Humphreys


3 Answers

That would fall into the case of the first part of the documentation:

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

A query that returns no result rows will return neither true, nor false, but a resource object.

However, the resource object will have no rows, i.e., mysql_num_rows() will return 0 and the first call to mysql_fetch_* will return FALSE. There are a number of ways that you can detect this situation, but calling mysql_num_rows() is probably one of the easiest.

like image 174
mellamokb Avatar answered Oct 23 '22 08:10

mellamokb


not sure its best way but i generally use mysql_num_rows to check for the result resource and if

$countt = mysql_num_rows($resource);
if($count>0)
{
//do further
}

like this in this case.

like image 21
Astha Avatar answered Oct 23 '22 07:10

Astha


to see what it returns, use

$result = mysql_query("SELECT * FROM  customers WHERE phone = $phoneNum", $link);
		
		$count = mysql_num_rows($result);

					echo $count;
like image 1
Asuquo12 Avatar answered Oct 23 '22 09:10

Asuquo12