首页 > 解决方案 > php程序准备与关联数组

问题描述

我需要使用准备语句来获得一系列结果,到目前为止我的经验都是程序化的。这是我需要帮助的代码:

在此之前,我有一个与数据库建立连接的 require 语句,并使用表单中的 $_POST 方法,我得到两个变量值,即 $town 和 $type。

$stmt = mysqli_smt_init($conn);
if (mysqli_stmt_prepare($stmt, "SELECT town, type, code FROM tab_01 WHERE town = ? AND type LIKE ?");
mysqli_stmt_bind_param($stmt, "ss", $town, $type);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($result) > 0) {
   while($row = mysqli_fetch_assoc($result)) {
      $townvalue[] = $row["town"];
      $typevalue[] = $row["type"];
   }
}
mysqli_stmt_close($stmt);

当然,它不会运行,因为在“if”和“while”语句中,我的语法来自非准备好的语句,而且肯定是错误的。

我需要回显结果的行(我的意思是结果的三列)。

在未准备好的声明中,我会这样写:

$sql = "SELECT town, type, code FROM tab_01 WHERE town='$town' AND type LIKE '$type'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
   while($row = mysqli_fetch_assoc($result)) {
      echo $row["town"];
      echo $row["type"];
      echo $row["code"];
   }
}
mysqli_free_result($result);
mysqli_close($conn);

以准备好的方式获得相同的正确语法是什么?谢谢你。

标签: phpprepared-statementassociative-array

解决方案


推荐阅读