Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP mysql_query not returning false

Tags:

php

mysql

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 Answers

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.

like image 124
artlung Avatar answered Jun 21 '26 05:06

artlung