php - 将 mysqli 存储结果作为字符串

标签 php html css

我正在尝试为从帖子中收到的 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_resultmysqli_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/

相关文章:

javascript - jQuery 中的宽度切换动画在 FireFox 中不起作用?

jquery - 使用 jquery 创建一个带有一些用户名和密码的登录页面

html - 为什么当我在另一个 div 上放置一个 margin-top 时,BODY 也会接受它?

html - 为什么 CSS Flexbox 不能正确调整最右边容器的大小?

php - 检查 MySQL 中是否存在记录(使用 PHP)?

Javascript 添加选项值

php代码一次将单个文件更新到mysql中的多个用户

html - CSS 是否可以将提交按钮与输入字段对齐?

css - 当 div 设置其父级的高度时,使 div 成为其容器的 100%

php - 从数据库字段中提取部分数据并创建多个变量