FewFlyBy FewFlyBy - 1 year ago 104
JSON Question

PHP json_encode returning single row only

So I have an associative array

This is the current output when I

[3] => 23
[5] => 5
[4] => 1

In the output above, the first one for example [3]=>23 where [3] is the id and 23 is the quantity I entered from a form:

My current data:

enter image description here

Note that in the image above, the quantity column is different from the quantity I'm entering from a form.

So far this is the code I've tried:

$statement = $conn->query("SELECT id, name, price, quantity FROM product WHERE id IN (".implode(',',$_SESSION['cart_items']).")");

while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;


print json_encode($data);

And this is the output:


As you can see it works, though I only get a single row which should be three.

Is there something wrong with my query?

Answer Source

You show that the array keys in the session array match the ids in the database. implode() implodes/joins the values in the array. So you need to implode the keys:

implode(',', array_keys($_SESSION['cart_items']))

Or flip the array:

implode(',', array_flip($_SESSION['cart_items']))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download