【问题标题】:Getting an associative array back from prepared statement从准备好的语句中获取关联数组
【发布时间】:2019-05-26 00:35:30
【问题描述】:

我正在尝试使用准备好的语句从 SQL 查询中获取关联数组。我没有尝试任何工作。在执行准备好的语句之前,我能够让它工作。我正在阅读很多相互冲突的信息以及似乎不适用于过程代码的 OO 和 PDO 信息。将来我可能会切换到其中一种风格,但我不想现在就重写整个网站。任何帮助是极大的赞赏。我有一个 item_template.php,它使用 rows['name']、rows['type'] 等读取数据。它正在工作 mysqli_fetch_assoc...我只是无法让 fetch_assoc 与准备好的语句一起工作。

  if ($searchname == NULL) {
    echo 'You must enter something to search for!';
    }else{
     $sql = "SELECT * FROM itemdb WHERE name LIKE ?";
     $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)) {
        header("Location: viewresults.php?error=sqlerror2");

        exit();
    }
    else{
      $searchname = "%".$searchname."%";
      mysqli_stmt_bind_param($stmt,"s", $searchname);
      mysqli_stmt_execute($stmt);
      mysqli_stmt_store_result($stmt);

      $resultcheck = mysqli_stmt_num_rows($stmt);
      echo $resultcheck;
        if ($resultcheck == 0) {
          echo 'No results found! Try again! ' . $resultcheck;
          exit();
        }else{
          $result = mysqli_stmt_get_result($stmt);
          echo $result;

          while ($row = mysqli_fetch_assoc($stmt)) {

          include("item_template.php");
          echo "SUCCESS";
        }
    }
  }
}

【问题讨论】:

  • 什么是$stmtmysqli_fetch_assoc 期望什么参数? (提示它是mysqli_result)。 var_dump 是你的朋友。
  • 我尝试将 mysqli_fetch_assoc 与 mysqli_stmt_store_result 一起使用,但也没有运气。我认为该语句将是 mysqli_result。当我不使用准备好的语句时,我没有任何问题......这就是让我完全不正常的原因。我不知道我在做什么,我认为我对某些事情感到困惑,哈哈。我一直试图弄清楚这一点。我找到的大多数示例和帮助都是 OO 和 PDO,它们之间的差异刚好足够,没有帮助。
  • 将 while ($row = mysqli_fetch_assoc($stmt)) 替换为 WHILE(null !== ($row = mysqli_fetch_assoc($stmt)))
  • 还是不行。这和我刚才的格式几乎一样?
  • 您尝试从语句中获取数据而不是结果 - mysqli_fetch_assoc($stmt) 应该是 mysqli_fetch_assoc($result)

标签: php mysql arrays mysqli


【解决方案1】:

您在数据库中使用什么编码?我使用utf8_general_ci 和西里尔字母。所以

mysqli_set_charset($conn, "utf8");

$conn=mysqli_connect(); 帮助我之后

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-05
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    相关资源
    最近更新 更多