問題描述
對于實際存在的電子郵件,我有一個簡單的準備聲明:
I have a simple prepared statement for an email that actually exists:
$mysqli = new mysqli("localhost", "root", "", "test");
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
exit();
}
$sql = 'SELECT `email` FROM `users` WHERE `email` = ?';
$email = 'example@hotmail.com';
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param('s', $email);
$stmt->execute();
if ($stmt->num_rows) {
echo 'hello';
}
echo 'No user';
}
結果:在應該回顯 hello
我在控制臺中運行了相同的查詢,并使用與上述相同的電子郵件得到了結果.
I ran the same query in the console and got a result using same email as above.
我也使用簡單的 mysqli 查詢進行了測試:
I tested using a simple mysqli query as well:
if ($result = $mysqli->query("SELECT email FROM users WHERE email = 'example@hotmail.com'")) {
echo 'hello';
}
結果:我所期望的hello
還有 $result
的 num_rows
是 1.
Also $result
's num_rows
is 1.
為什么準備好的語句的num_row
不大于0?
Why is the prepared statment's num_row
not greater than 0?
推薦答案
當您通過 mysqli 執行語句時,結果實際上并不在 PHP 中,直到您獲取它們——結果由數據庫引擎保存.所以mysqli_stmt
對象無法知道執行后立即有多少結果.
When you execute a statement through mysqli, the results are not actually in PHP until you fetch them -- the results are held by the DB engine. So the mysqli_stmt
object has no way to know how many results there are immediately after execution.
像這樣修改你的代碼:
$stmt->execute();
$stmt->store_result(); // pull results into PHP memory
// now you can check $stmt->num_rows;
查看手冊
這不適用于您的特定示例,但如果您的結果集很大,$stmt->store_result()
將消耗大量內存.在這種情況下,如果您只關心是否至少返回了一個結果,請不要存儲結果;相反,只需檢查結果元數據是否不為空:
This doesn't apply to your particular example, but if your result set is large, $stmt->store_result()
will consume a lot of memory. In this case, if all you care about is figuring out whether at least one result was returned, don't store results; instead, just check whether the result metadata is not null:
$stmt->execute();
$hasResult = $stmt->result_metadata ? true : false;
查看手冊
這篇關于mysqli 準備好的語句 num_rows 返回 0 而查詢返回大于 0的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!