检查php prepare语句中是否为空


check if empty in php prepare statement

在我准备的语句中,我可以检索MySQL返回的值,但如果MySQL没有返回任何数据,则无法通知用户。

以下是我准备的声明的代码。

$database是mysqli连接的对象。

$stmt = $database->prepare($qryCallProc);
$stmt->bind_param('iss',$userId,$trendType,$university);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($param1,$param2);
while($stmt->fetch) {
    print_r($param1);
}
$stmt->free_result();
$stmt->close();

我甚至尝试在$stmt->bind_result($param1,$param2)之后使用以下代码,但没有用:

if(!$stmt->fetch()) {
    print_r("there is no data");
} elseif (is_null($stmt->fetch())) {
    print_r("there is no data");
}

我的代码中是否遗漏了什么,或者有其他方法可以做到这一点?

在使用num_rows 之前必须使用store_result()

您可以先使用num_rows来检查您的查询是否产生行:

$stmt->store_result();
if($stmt->num_rows > 0) {
    $stmt->bind_result($param1,$param2);
    while($stmt->fetch) {
        echo $param1;
    }
} else {
    // sorry no rows found
}

您可以先使用num_rows来检查您的查询是否产生行:

if($stmt->num_rows > 0) {
    $stmt->store_result();
    $stmt->bind_result($param1,$param2);
    while($stmt->fetch) {
        echo $param1;
    }
} else {
    // sorry no rows found
}