结果集为空时显示一条消息
问题描述:
在以下代码中,如果结果集为空,则代码将继续处理结果。我要显示的只是查询失败。
In the following code, if the resultset is empty, the code continues to process the result. What I want instead is to just display "Query failed." when there are no results.
$connInfo = array('UID'=>$user, 'PWD'=>$passwd, 'Database'=>$database);
$dbconn = sqlsrv_connect($server, $connInfo);
if($dbconn === false){
die("<br />Error connecting to the database.<br />");
}
//SQL Query
$query = "SELECT ... FROM somehwere";
//Run Query
$qresult = sqlsrv_query($dbconn, $query);
if($qresult === false) {
die('Query failed.');
}
?>
...more code...
答
$ qresult如果未找到任何行,则将包含一个空结果集,但仍不会得出false。
$qresult will contain an empty result set if no rows are found, but it still won't evaluate to false.
请尝试以下函数:
http:// www .php.net / manual / en / function.sqlsrv-num-rows.php
因此:
if(!sqlsrv_num_rows($qresult)) {
die('Query failed.');
}
而不是:
if($qresult === false) {
die('Query failed.');
}