我在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'];
}
答案 0 :(得分: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;
}
答案 1 :(得分:0)
改变,
$stmt->store_result();
到
$result = $stmt->store_result();
和
更改,
$row = $stmt->fetch_assoc();
到
$row = $result->fetch_assoc();
答案 2 :(得分: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();
答案 3 :(得分: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'];
答案 4 :(得分:0)
Asciiom指出,最好使用mysqlnd。但是,如果您处于一种不允许安装mysqlnd的奇怪情况,那么仍然可以将数据放入没有它的关联数组中。尝试使用此答案中的代码 Mysqli - Bind results to an Array