dennis ramli dennis ramli - 23 days ago 5
MySQL Question

using foreach multiple times

How can I use

foreach
multiple times?

<?php
$query = $db->query('SELECT tbl_stok.id_stok,
tbl_stok.id_provinsi,
tbl_stok.id_kabupaten,
tbl_stok.tanggal,
tbl_stok.mie_instan,
tbl_stok.beras,
tbl_stok.telur
FROM `tbl_stok` INNER JOIN tbl_wilayah ON tbl_stok.id_provinsi = tbl_wilayah.id_user
');
$query->fetchAll;
?>


I want to use the first
foreach
to show the data tables:

<?php foreach($query as $row){
echo $row['beras'];
}?>


Then I want to use the second
foreach
for chart:

<?php foreach($query as $row){
echo $row['telur'];
}?>


However, this
foreach
works only once.

Answer

You can do this:

1) save your data to an array.

foreach($query as $row){
    $data[]= $row;
}

2) use your array in every loop you want as many time you want

foreach($data as $row){
    echo $row['beras'];
}

foreach($data as $row){
    echo $row['telur'];
}
Comments