问题
If I run this code, the if-clause won't return false even though the data record doesn't exist in the database myDB
in table myTable
. I don't know what's wrong..
// MySQLi-Connection...
$result = $mysqli->query("SELECT * FROM `myDB`.`myTable` WHERE `itemtype` = 'comment' AND `itemID` = 3");
if ($result) {
echo "record found!";
} else {
echo "record not found!";
}
The record with itemID
= 3 doesn't exist, but my if-clause says that the $result returns true..
回答1:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries
mysqli_query() will return a mysqli_result object. For other successful queries
mysqli_query() will return TRUE.
#Reference PHP Manual
You can use
$result = $mysqli->query("YOUR QUERY"));
if($result->num_rows){
// Records Found
}else{
// Empty Result
}
回答2:
Its much logical to use mysqli_num_rows here:
$result = $mysqli->query("SELECT * FROM `myDB`.`myTable` WHERE `itemtype` = 'comment' AND `itemID` = 3");
if($result->num_rows > 0) {
echo 'record found';
} else {
echo 'query is ok but no results found';
}
You can't put a mysqli_result object in your if since it will still evaluate as TRUE even if it yields 0 rows.
回答3:
Your PHP if statement will evaluate to TRUE, as an empty mysql results set does not mean it is a failed query. The query ran ok, and mysql retrieved 0 rows, hence $result evaluates to true.
To check if a valid row has been retrieved, try:
if ( ! empty($result) ) {
echo "record found!";
} else {
echo "record not found!";
}
来源:https://stackoverflow.com/questions/24572271/php-mysqli-query-doesnt-return-true-or-false