我有一个php页面与下面的代码。MySQL查询运行正常,但我尝试添加了一条IF语句,但该语句不起作用。if(!isset($result))语句应该能够捕获表中只包含将来的日期时间值的情况。我显然没有正确使用它,或者我应该使用其他东西-比如if(empty())?
<?php
include 'quantitytest_config.php';
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("grace59_countdown",$dbhandle)
or die("Could not select countdown");
//execute the SQL query and return records
$result = mysql_query(
"SELECT items
FROM cases
WHERE datetime<=NOW()
Limit 1 ");
// check if there are only future dates in Database
if(!isset($result)){
echo "9999";
} else {
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "Quantity:".$row{'items'}."<br>";
}
}
//close the connection
mysql_close($dbhandle);
?>发布于 2013-04-19 06:55:23
您正在寻找:
if(mysql_num_rows($result) == 0){
echo "9999";
} else {文档:http://www.php.net/manual/en/function.mysql-num-rows.php
当您说$result = mysql_query时,您将为$result赋值,因此即使没有找到行,现在也会设置变量,因此isset()将不起作用。
但是你真的不应该使用mysql_*函数。相反,请注意准备好的语句。PDO或mysqli。更多信息可以在这里找到:http://www.php.net/manual/en/function.mysql-query.php (红色方框)
发布于 2013-04-19 06:57:58
var isset -如果
存在并且具有非NULL的值,则返回TRUE,否则返回FALSE。
但是如果查询没有结果,$result将是一个有效的MySQL资源事件。
从docs
表示SELECT、SHOW、DESCRIBE、EXPLAIN和其他返回结果集的语句,mysql_query()在成功时返回资源,在错误时返回FALSE。
对于其他类型的SQL语句,如INSERT、UPDATE、DELETE、DROP等,mysql_query()在成功时返回TRUE,在出错时返回FALSE。
使用mysql_num_results()检测结果集是否为空:
if(mysql_num_rows($result) == 0) {
echo 'no results';
}还要注意的是,您不应该在新代码中使用mysql_*函数,因为PHP开发人员已经将该扩展标记为已弃用。请改用PDO或mysqli。
发布于 2013-04-19 07:08:05
不要忘记mysql_query可以返回false,所以:
if($result){
if(mysql_num_rows($result) == 0){
echo "9999";
}
}https://stackoverflow.com/questions/16094409
复制相似问题