mysqli返回空结果 - 如何显示

时间:2012-10-29 16:13:51

标签: php mysqli

我有以下PHP,它基本上得到MySQL查询的结果:

$q2 = "SELECT FIELD FROM TABLENAME WHERE ID = 1;";
$con = new mysqli($server, $user, $pass);
if (mysqli_connect_errno()) 
{
    $error = mysqli_connect_error();
    exit();
}
else
{   
    $res = mysqli_query($con, $q2);
    if ($res)
    {   
        while($row = mysqli_fetch_assoc($res))
        {
            PRINT "THERE WAS A RESULT HERE: "; 
        }
    }
    else
    {
        $error = mysqli_error();
        exit();
    }
    mysqli_free_result($res);   
};
mysqli_close($con);

但有时,它会返回一个空值。这是有效的,基于父应用程序的工作方式,但是如何检测到该空行并返回"这是一个空行:"?

4 个答案:

答案 0 :(得分:4)

您可能想在PHP手册中查找mysqli_num_rows()。它可以让您查看上一个查询生成的结果集中有多少行。您可以使用行计数来确定是显示结果还是“无匹配结果”消息。

答案 1 :(得分:2)

我希望这会有所帮助。

if ($res)
{   
    if($res->num_rows) {
        while($row = mysqli_fetch_assoc($res))
        {
           PRINT "THERE WAS A RESULT HERE: "; 
        }
    }
    else {
          PRINT "THERE WAS A EMPTY ROW: "; 
    }
}

参考:php.net

答案 2 :(得分:0)

谢谢你,我最终得到了:

$q2 = "SELECT FIELD FROM TABLENAME WHERE ID = 1;";
$con = new mysqli($server, $user, $pass);
if (mysqli_connect_errno()) 
{
    $error = mysqli_connect_error();
    exit();
}
else
{   
$res = mysqli_query($con, $q2);

$row_cnt = mysqli_num_rows($res);

if ($row_cnt == 0)
{
        PRINT "THERE WAS NO RESULT: "; 
 }

else
{    
if ($res)
{   
    while($row = mysqli_fetch_assoc($res))
    {
        PRINT "THERE WAS A RESULT HERE: "; 
    }
}
else
{
    $error = mysqli_error();
    exit();
}
mysqli_free_result($res);   
}
};
 mysqli_close($con);

答案 3 :(得分:0)

我的php函数查询句柄:

private function query($sql_query){

        $result = $this->connection->query($sql_query);

        if(!$result){           //query fail
            throw new Exception($this->connection->error.$sql_query);
        }else {//                 "SUCCESS";
            if(!$result->num_rows)
            {
                throw new Exception("THERE WAS NO RESULT: "); 
             }
            for ($res = array(); $tmp = $result->fetch_array(MYSQLI_BOTH);){ 
                $res[] = $tmp;                
            }
           return $res;
        }
    }