5

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

5 回答 5

10

变量 $stmt 的类型是 mysqli_stmt,而不是 mysqli_result。mysqli_stmt 类没有为其定义方法“fetch_assoc()”。

您可以通过调用其 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;
}
于 2012-08-29T12:53:28.733 回答
0

改变,

$stmt->store_result();

$result = $stmt->store_result();

改变,

$row = $stmt->fetch_assoc();

$row = $result->fetch_assoc();
于 2012-08-29T12:55:18.093 回答
0

你错过了这一步

$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();
于 2012-08-29T13:02:15.250 回答
0

Asciiom 指出,最好使用 mysqlnd。但是,如果您处于不允许安装 mysqlnd 的奇怪情况,则仍然可以在没有它的情况下将您的数据放入关联数组中。尝试使用此答案中的代码 Mysqli - Bind results to an Array

于 2018-04-02T19:46:03.707 回答
0

我意识到这段代码是作为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'];
于 2015-10-30T20:34:46.670 回答