問題描述
我目前正在編寫一個登錄腳本,我得到了這個代碼:
I'm currently working on a login script, and I got this code:
$selectUser = $db->prepare("SELECT `id`,`password`,`salt` FROM `users` WHERE `username`=?");
$selectUser->bind_param('s', $username);
$selectUser->execute();
if ($selectUser->num_rows() < 0)
echo "no_user";
else
{
$user = $selectUser->fetch_assoc();
echo $user['id'];
}
這是我得到的錯誤:
致命錯誤:未捕獲的錯誤:調(diào)用未定義的方法mysqli_stmt::fetch_assoc()
Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetch_assoc()
我嘗試了各種變體,例如:
I tried all sorts of variations, like:
$result = $selectUser->execute();
$user = $result->fetch_assoc();
還有更多……沒有任何效果.
and more... nothing worked.
推薦答案
那是因為 fetch_assoc
不是 mysqli_stmt
對象的一部分.fetch_assoc
屬于 mysqli_result
類.可以使用mysqli_stmt::get_result
先獲取一個結(jié)果對象,然后調(diào)用fetch_assoc
:
That's because fetch_assoc
is not part of a mysqli_stmt
object. fetch_assoc
belongs to the mysqli_result
class. You can use mysqli_stmt::get_result
to first get a result object and then call fetch_assoc
:
$selectUser = $db->prepare("SELECT `id`,`password`,`salt` FROM `users` WHERE `username`=?");
$selectUser->bind_param('s', $username);
$selectUser->execute();
$result = $selectUser->get_result();
$assoc = $result->fetch_assoc();
或者,您可以使用 bind_result
將查詢的列綁定到變量并使用 fetch()
代替:
Alternatively, you can use bind_result
to bind the query's columns to variables and use fetch()
instead:
$selectUser = $db->prepare("SELECT `id`,`password`,`salt` FROM `users` WHERE `username`=?");
$selectUser->bind_param('s', $username);
$selectUser->bind_result($id, $password, $salt);
$selectUser->execute();
while($selectUser->fetch())
{
//$id, $password and $salt contain the values you're looking for
}
這篇關(guān)于在準備好的語句上使用 fetch_assoc (php mysqli)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!