如何捕捉php mysqli查询的空结果


How to catch empty results of a php mysqli query

查询:

$stmt = $dbconnect->prepare("SELECT `title`,`description`,`postid` FROM `posttd` WHERE MATCH `title` AGAINST ( ? IN BOOLEAN MODE)");
$stmt->bind_param('s', $value);
$stmt->execute();

$value的值为'test1', 'other'和'test2'

值'other'是mysql的停止词。因此,当它通过查询时,结果为空。

只是想知道如何捕获它,以便我可以将它从$value数组中取出。

var_dump($stmt->execute());将使bool(true)在所有三个上都让步。

我尽可能不希望在查询中运行$value之前过滤它的停止词。

$stmt->execute();之后的var_dump($stmt)将得到以下结果:

test1 var_dump

object(mysqli_stmt)#2 (9) { ["affected_rows"]=> int(-1) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(1) ["field_count"]=> int(3) ["errno"]=> int(0) ["error"]=> string(0) "" ["sqlstate"]=> string(5) "00000" ["id"]=> int(1) } 

test2 var_dump

object(mysqli_stmt)#2 (9) { ["affected_rows"]=> int(-1) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(1) ["field_count"]=> int(3) ["errno"]=> int(0) ["error"]=> string(0) "" ["sqlstate"]=> string(5) "00000" ["id"]=> int(3) } 
其他var_dump

object(mysqli_stmt)#6 (9) { ["affected_rows"]=> int(-1) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(1) ["field_count"]=> int(3) ["errno"]=> int(0) ["error"]=> string(0) "" ["sqlstate"]=> string(5) "00000" ["id"]=> int(2) } 

唯一的区别是object(mysqli_stmt)#6

任何想法?

使用

 if($stmt->rowCount() > 0) {
   // do what you want here
}

上面的语句确保如果有数据,那么只有它会进入条件

你应该直接使用

if($res = $stmt->get_result()) {
    //this means query returned some rows
}
else {
    //and this means the result was empty
}

并且,是的,它确实需要您的php用mysqld(本机驱动程序)编译,否则您将获得未声明的mysqli_stmt::get_result()函数错误或类似的东西。

所以我无法使用内置函数捕获它。相反,我做了一个简单的测试来捕捉空结果。

$bindarray = array('+test1','+other','+test2');
foreach($bindarray as $key=>$value)
{
echo $value; // NOTE1: This echo prints +test1, +other, and +test2
$stmt = $dbconnect->prepare("SELECT `title`,`description`,`postid` FROM `posttd` WHERE MATCH `title` AGAINST ( ? IN BOOLEAN MODE)");
$stmt->bind_param('s', $value);
echo 'Bind:'.$value; // NOTE2: This echo prints +test1, +other, and +test2
$stmt->execute();
echo 'Execute:'.$value; // NOTE3: This echo prints +test1, +other, and +test2
$stmt->bind_result($rtitle,$rdescription,$rpostid);
    while($stmt->fetch())
    {
        echo 'Fetch:'.$value; // NOTE4: This echo prints +test1 and +test2 ONLY
        if(!empty($value))
        {
            if(!in_array($value, $goodvalues))
            {
                array_push($goodvalues,$value);
            }
        }
    }
}

所以你可以看到在NOTE4 $value没有获取任何东西($stmt->fetch()),所以它没有通过while循环,所以它没有被包含在$goodvalues数组中,所以我能够从数组中分离停止词。

如果您能够使用内置函数捕获停止词,请共享。

谢谢