简体   繁体   中英

JSON output for SELECT with Prepared Statement

I am trying to encode the results from SELECT query with prepared statement into JSON output. 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 ? 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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