Noob_coder Noob_coder - 6 months ago 23
PHP Question

How to add item in array using nested for each loop in php

I am trying to create array of row object from table in PHP. I am using the below code to do it, but I am not getting the expected result.

I want the below format:

[{"fName":"apple","fprice":11,"quantity":2},{"dName":"orange","fprice":31,"quantity":6}]


But using the following code I am getting only the last row last column value:

$query = 'select fname,fprice,imgpath,fdesc,cid from food_data';
$stid = oci_parse($conn, $query);
oci_execute($stid, OCI_DEFAULT);
while ($row = oci_fetch_assoc($stid)) {
foreach ($row as $key=>$val) {
//echo $item." <br />";
$data = array(
array(''.$key.''=>''.$val.'') );
}
//echo "\n";
}

Answer

Even easier to use oci_fetch_all():

oci_fetch_all($stid, $data, null, null, OCI_FETCHSTATEMENT_BY_ROW);

$data will be an array of rows that are arrays of column names and column data.

Comments