获取关联数组时如何消除致命错误

2021-12-25 00:00:00 php mysqli

我在我的 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;
}

相关文章