gpt4 book ai didi

php - 获取关联数组时如何删除 fatal error

转载 作者:可可西里 更新时间:2023-11-01 13:45:38 24 4
gpt4 key购买 nike

我在我的 php/mysqli 代码中收到一个 fatal error ,该错误在第 46 行指出:

Fatal error: Call to undefined method mysqli_stmt::fetch_assoc() in ...

我只想知道如何消除这个 fatal error ?

它指向的代码行在这里:

$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()”。

您可以通过调用 mysqli_stmt 对象的 get_result() 方法从您的 mysqli_stmt 对象中获取一个 mysqli_result 对象。 为此,您需要安装 mysqlInd 驱动程序!

$result = $stmt->get_result();
row = $result->fetch_assoc();

如果您没有安装驱动程序,您可以像这样获取结果:

$stmt->bind_result($dbUser, $dbEmail);
while ($stmt->fetch()) {
printf("%s %s\n", $dbUser, $dbEmail);
}

所以你的代码应该变成:

$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;
}

关于php - 获取关联数组时如何删除 fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12178373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com