如何使用 mysqli 使用 php 准备语句在数据表中显示数据



当我使用 php mysqli 在表中显示结果时,此代码工作正常(使用数据表)

$result = mysqli_query($con, $query);
if (!$result) {
    die("Database query failed.");
}
$res = array();
while ($row = $result->fetch_array()) {
    array_push($res, $row);
}
echo json_encode($res);
{
data: "distributor_name"
}, {
data: "order_date"
}, {
data: "product_name"
}, {
data: "nsp"
}, {
data: "region"
}, {
data: "current-sales"
}, {
data: "closing-balance"
}, {
data: "CBTotal"
},{
data: "CSTotal"
},{
data: "pro_ID"
}

但是我想使用php准备语句,这段代码有什么错误?如何在那里传递 php 变量?

$stmt->bind_result($distributor_name, $order_date, $product_name, $nsp, $region, $pro_ID, $current_sales, $closing_balance);
 $json = array();
while($row = $stmt->fetch()){
    array_push($json, $row);
}
echo json_encode($json);
    $stmt -> close();

假设您有一个这样的表:

CREATE TABLE `product` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `distributor_name` varchar(255) DEFAULT NULL,
  `product_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

有数据:

id   distributor_name    product_name
1    distributor1        product2
2    distributor2        product3
3    distributor1        product4

假设您想获得distributor1的产品。你做这样的事情:

<?php
$mysqli = new mysqli("127.0.0.1", "root", "password", "test");
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %sn", mysqli_connect_error());
    exit();
}
$distributor = "distributor1";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM `product` WHERE `distributor_name` = ?")) {
    /* bind parameters for markers */
    $stmt->bind_param("s", $distributor);
    /* execute query */
    $stmt->execute();
    /* bind result variables */
    $stmt->bind_result($id, $distributorName, $product);
    /* fetch values */
    $results = [];
    while ($stmt->fetch()) {
        $results[] = [$id, $distributorName, $product];
    }
    echo json_encode($results);
    /* close statement */
    $stmt->close();
}
/* close connection */
$mysqli->close();

更新

错误出在以下代码中:

   while($row = $stmt->fetch()){
       array_push($json, $row);
   }

$stmt->fetch()返回truefalsenull,你的json可能只保存true值。

最新更新