0

我有以下 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

4 回答 4

4

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

于 2012-10-29T16:18:54.840 回答
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

于 2012-10-29T17:02:55.753 回答
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);
于 2012-10-29T17:19:54.470 回答
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;
        }
    }
于 2015-05-25T11:50:19.463 回答