View Full Version : Retrieving Data from array

05-26-2011, 08:08 PM
Hi, so I have been trying to come up with a way to do a mysql query and store the results so that I can then access them and create an html table.

Here is the code for the query and array:

$query = "SELECT * FROM table WHERE user_id = '" . $_SESSION['user_id'] . "'";
$data = mysqli_query($dbc, $query);
$array = array();
while ($row = mysqli_fetch_array($data)) {
array_push($array, $arr = array ($a => $row['a'], $b => $row['b'], $c => $row['c], $d => $row['d'], $e => $row['e], $f => $row['f']));

This should create a large array of arrays, depending on how many rows of data result from the query.

Can someone help me with the code that will now take these arrays and create an html table with the results? Also needs to make sure if there are no results, nothing is produced.

05-26-2011, 08:45 PM
Where are these $a through $f variables coming from? As is, you'd end up with a single field appended as you are trying to force it to null offset (making it irretrievable via ArrayAccess, iteration should still work).
That's way too much work. Unless you need to actually force it on a different key, you can simply use:

$array = array();
while ($row = mysql_fetch_assoc($data))
$array[] = $row;

As for iterating it, a simple foreach can be done for that:

print '<table>';
foreach ($array AS $record)
print '<tr>';
foreach ($record AS $item)
printf('<td>%s</td>', $item);
print '</tr>';
print '</table>';

Simple as that. Its impossible to have an empty entry from the database itself (as it would be abandoned as a non-matching entry), so there is no need to conditionally check it. Fields could be empty, but you'll need to make sure that the td's are still provided for it if you intend to use a table.

05-26-2011, 09:45 PM
The variables were made just to keep track of the data, your right, it offsets it.

I was trying to do this because there can be multiple rows of data, and wanted to be able to create a table with each data row matching with each html row.

Thanks for your help.