简体   繁体   English

带有准备语句的 SELECT 的 JSON 输出

[英]JSON output for SELECT with Prepared Statement

I am trying to encode the results from SELECT query with prepared statement into JSON output.我正在尝试将带有准备好的语句的 SELECT 查询的结果编码为 JSON 输出。 I have the following code but I can't get it working.我有以下代码,但无法正常工作。 Any help would be greatly appreciated.任何帮助将不胜感激。

$query = "SELECT Item.ItemID, Item.ItemName FROM Items"
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stmt->store_result();
    $numrows = $stmt->num_rows;
    $stmt->bind_result($ItemID, $ItemName);

 for ($i=0; $i <$numrows; $i++) {
    $stmt->fetch();

$JSONArray = ["ItemID" => $ItemID,
             "ItemName" => $ItemName
             ]

echo json_encode($JSONArray);
}

You should always add the items to the container array, not overwrite the whole array and encode & echo only once:您应该始终将项目添加到容器数组中,而不是覆盖整个数组并且只编码和回显一次:

...

$JSONArray = []; // initialize to empty array
for ($i=0; $i <$numrows; $i++) {
    $row = $stmt->fetch();
    $ItemID = $row['ItemID'];
    $ItemName = $row['ItemName'];
    // add the new item in each iteration
    $JSONArray[] = ["ItemID" => $ItemID,
             "ItemName" => $ItemName
             ];
}
echo json_encode($JSONArray);

Don't you think it should be Items not Item ?你不认为它应该是Items而不是Item吗? also there's missing quote and semicolon.还有缺少引号和分号。

$query = "SELECT Items.ItemID, Items.ItemName FROM Items";
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();

echo json_encode($result);

Also for convention I'd suggest you to keep lowercase table names.同样为了约定,我建议您保留小写的表名。 :) :)

When creating the PDO Object add:创建 PDO 对象时添加:

array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")

eg:例如:

$db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

that helped in my case : )这对我有帮助:)

as seen on https://stackoverflow.com/a/7030557/5764766如在https://stackoverflow.com/a/7030557/5764766 上看到的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM