問題描述
我在我的 php/mysqli 代碼中收到一個致命錯誤,它在第 46 行指出:
I am receiving a fatal error in my php/mysqli code which states that on line 46:
Fatal error: Call to undefined method mysqli_stmt::fetch_assoc() in ...
我只想知道如何消除這個致命錯誤?
I just want to know how can I remove this fatal error?
它指向的代碼行在這里:
The line of code it is pointing at is here:
$row = $stmt->fetch_assoc();
原始代碼:
$query = "SELECT Username, Email FROM User WHERE User = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$user);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbUser, $dbEmail);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
if ($numrows == 1){
$row = $stmt->fetch_assoc();
$dbemail = $row['Email'];
}
更新代碼:
$query = "SELECT Username, Email FROM User WHERE User = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$user);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbUser, $dbEmail);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
if ($numrows == 1){
$row = $stmt->fetch_assoc();
$dbemail = $row['Email'];
}
推薦答案
變量 $stmt 的類型是 mysqli_stmt,而不是 mysqli_result.mysqli_stmt 類沒有為其定義方法fetch_assoc()".
The variable $stmt is of type mysqli_stmt, not mysqli_result. The mysqli_stmt class doesn't have a method "fetch_assoc()" defined for it.
您可以通過調用其 get_result() 方法從 mysqli_stmt 對象中獲取 mysqli_result 對象.為此,您需要安裝 mysqlInd 驅動程序!
You can get a mysqli_result object from your mysqli_stmt object by calling its get_result() method. For this you need the mysqlInd driver installed!
$result = $stmt->get_result();
row = $result->fetch_assoc();
如果您沒有安裝驅動程序,您可以像這樣獲取結果:
If you don't have the driver installed you can fetch your results like this:
$stmt->bind_result($dbUser, $dbEmail);
while ($stmt->fetch()) {
printf("%s %s
", $dbUser, $dbEmail);
}
所以你的代碼應該變成:
So your code should become:
$query = "SELECT Username, Email FROM User WHERE User = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$user);
// execute query
$stmt->execute();
// bind variables to result
$stmt->bind_result($dbUser, $dbEmail);
//fetch the first result row, this pumps the result values in the bound variables
if($stmt->fetch()){
echo 'result is ' . dbEmail;
}
這篇關于獲取關聯數組時如何消除致命錯誤的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!