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?
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.
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.
to see what it returns, use
$result = mysql_query("SELECT * FROM customers WHERE phone = $phoneNum", $link);
$count = mysql_num_rows($result);
echo $count;
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