当sqlsrv_fetch_array无返回时隐藏错误


hidding errors when sqlsrv_fetch_array return nothing

从数据库读取记录。但是当我的查询失败时,我有错误,例如:未定义的变量。我知道这很正常,因为查询在数据库中找不到任何东西。如何隐藏错误?我在试这个:

$result = sqlsrv_query($conn, "MY SQL QUERY WHERE status='running'))");
if ($result === false) {
    $note = 'unknown';
    $code = 'unknown';

    } else { 
    while($row = sqlsrv_fetch_array($result))
  {
    $note = $row['note'];
    $code = $row['code'];   
  }
}
echo $note;
echo $code;

逻辑上应该是好的?

如果没有结果,则$result不为假,但没有行。您可以通过首先将$note$code变量设置为默认值来解决这个问题:

$result = sqlsrv_query($conn, "MY SQL QUERY WHERE status='running'))");
$note = 'unknown';
$code = 'unknown';
if ($result !== false) {
    while($row = sqlsrv_fetch_array($result))
    {
        $note = $row['note'];
        $code = $row['code'];   
    }
}
echo $note;
echo $code;