【问题标题】:How to show data in datatables using php prepared statement using mysqli?如何使用 mysqli 使用 php 准备语句在数据表中显示数据?
【发布时间】:2018-04-13 18:55:49
【问题描述】:

当我使用 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();

【问题讨论】:

  • 为什么一定要使用prepared statement?

标签: php json mysqli datatables prepared-statement


【解决方案1】:

假设你有一个这样的表:

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: %s\n", 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-&gt;fetch() 返回 truefalsenull ,您的 json 可能只包含 true 值。

【讨论】:

  • 非常感谢我也这样做了,但我的问题是我应该像这样使用这些变量吗? {数据:“$distributor_name”},{数据:“$order_date”},
  • 请说明您到底想达到什么目的?不确定我是否理解你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 2016-07-22
  • 2014-03-20
  • 1970-01-01
  • 2015-04-16
相关资源
最近更新 更多