为什么搜索会引发对未定义错误方法stmt :: fetch_row()的调用?

时间:2019-01-28 23:49:30

标签: php mysql mysqli

当我尝试使用SELECT语句查询数据库时,它工作正常,但是当我尝试过滤通过将LIKE子句附加到原始查询中而返回的行时,它将引发致命错误:调用未定义的方法mysqli_stmt :: fetch_row( )

if (isset($_POST["search"]))
{
    $searchString = "%{$_POST['search']}%";
    $queryStringAppend = " WHERE name LIKE ? OR state LIKE ?";
            $stmt = $mysqli->prepare("SELECT COUNT(*) FROM $tableName " . $queryStringAppend);
    //|| die("Ooops! Error occured: <br/>" . $mysqli->error);
    $stmt->bind_param("ss", $searchString, $searchString);

    $stmt->execute();
    $stmt->store_result();
    if ($mysqli->error)     // CHECK IF ERROR HANDLER IS WORKING
        die("Query failed: <br />" . $mysqli->error);
}
 else
{
    $stmt = $mysqli->query("SELECT COUNT(*) FROM $tableName ");
    if ($mysqli->error)
        die("Query failed: <br />" . $mysqli->error);
}

$totalRowCount = $stmt->fetch_row()[0];  // This is the line where the error is thrown

未设置$ _POST [“ search”]时,查询工作正常,并显示所有结果。但是,如果我尝试过滤,则会引发错误:-(

1 个答案:

答案 0 :(得分:2)

这是因为fetch_row是mysqli_result而不是mysqli_stmt的方法 您需要先存储结果

    $results = $stmt->get_result()
    $results->fetch_row()[0];

在第二个if中,mysqli->query("")直接返回一个mysqli_result对象,这就是为什么它无错误执行的原因;