tags:

views:

401

answers:

6

Just learning PHP and I'm having some trouble understanding mysql_query. My understanding is that mysql_query is supposed to return FALSE if the record is not found. However, it seems that it always returns true because "FOUND!" is always the result:

$q = "SELECT * FROM users WHERE username = 'doesnotexist'";

$r = mysql_query($q);

if (!$q) {
 echo "<p>NOT FOUND!</p>";
} else {
 echo "<p>FOUND!</p>";
}

mysql_close();

Thanks in advance for any light you can shed.

+1  A: 

You are checking the '$q' variable (your sql statement) instead of the '$r' variable (the mysql result)

Jarod Elliott
A: 

Your 'if (!$q)' should be 'if (!$r)' I think.

jerryjvl
+7  A: 

mysql_query returns false if there is an error, not if there are no results found. From the documentation:

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.

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

If you want to check to see if there were results returned by your query, use mysql_num_rows(). See the documentation:

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.

artlung
+1  A: 
if (empty($r)) {
        echo "<p>NOT FOUND!</p>";
} else {
        echo "<p>FOUND!</p>";
}

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
kylex
A: 

jerryjvl is right :P

popcornman
A: 

if that dosen't work, try this:

<?php
$q = "SELECT * FROM users WHERE username = 'doesnotexist'";
$r = mysql_query($q);
if (!mysql_num_rows($r) >= 1) {
        echo "<p>NOT FOUND!</p>";
} else {
        echo "<p>FOUND!</p>";
}
mysql_close();
?>
popcornman