0

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);
}
Tomasz Kowalczyk
  • 10,472
  • 6
  • 52
  • 68
Luke
  • 407
  • 2
  • 10
  • 22

3 Answers3

2

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);
Zoli Szabó
  • 4,366
  • 1
  • 13
  • 19
1

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. :)

imrealashu
  • 5,089
  • 4
  • 16
  • 28
0

When creating the PDO Object add:

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

e.g.:

$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