如何删除获取assoc数组时的致命错误


How to remove the fatal error when fetching an assoc array

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

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

我只是想知道如何删除这个致命错误?

它指向的代码行在这里:

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

更改,

$stmt->store_result();

$result = $stmt->store_result();

更改,

$row = $stmt->fetch_assoc();

$row = $result->fetch_assoc();

您错过了这一步

$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$res = $stmt->get_result(); // you have missed this step
$row = $res->fetch_assoc();

我意识到这段代码是作为stackoverflow上某个地方的答案提供的:

//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();

我试着用它来获取行数,但意识到我不需要$stmt->store_result();行,它也没有得到我的编号。我用过这个:

$result      = $stmt->get_result();
$num_of_rows = $result->num_rows;
......
$row         = $result->fetch_assoc();
$sample      = $row['sample'];

正如Asciom指出的那样,最好使用mysqlnd。但是,如果你处于一个不允许安装mysqlnd的奇怪情况下,仍然可以在没有它的情况下将数据放入关联数组Mysqli-将结果绑定到数组