我正在尝试为从帖子中收到的 bookName 找到相应的 bookId,以避免因书名中的引号引起的错误。
我试图将参数绑定(bind)到 $stmt
作为 $bookName
并将结果存储为 $stmt
但是
echo $stmt;
给出这个错误:
Recoverable fatal error: Object of class mysqli_stmt could not be converted to string
所以我不确定我在做什么...
$bookName = trim($_POST['bookName']);
$sql = "SELECT bookId FROM Book WHERE bookName = ?";
if($stmt = mysqli_prepare($conn, $sql)){
mysqli_stmt_bind_param($stmt, "s", $bookName);
if((mysqli_stmt_execute($stmt))){
mysqli_stmt_store_result($stmt);
}
else{
header("location: error.php");
}
}
我要将 bookId 保存为 $bookId
下面的代码完成了我所需要的
if($stmt = mysqli_prepare($conn, $sql)){
mysqli_stmt_bind_param($stmt, "s", $bookName);
if((mysqli_stmt_execute($stmt))){
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
{
foreach ($row as $r)
{
$bookId = $r;
}
}
}
else{
header("location: error.php");
}
}
最佳答案
我认为您对 mysqli_stmt_store_result
和 mysqli_stmt_get_result
这两个函数感到困惑,必须在文档中查看此链接。
您必须使用mysqli_stmt_get_result
函数。
mysqli_stmt_get_result Documentation Link
if((mysqli_stmt_execute($stmt))){
mysqli_stmt_store_result($stmt);
}
将上面的代码替换为
if((mysqli_stmt_execute($stmt))){
// mysqli_stmt_store_result($stmt); not to use
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
echo $row; //as i dont have database details i hope this work.
}
有关更多认证,请参阅文档链接中的示例二。
关于php - 将 mysqli 存储结果作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52093000/