PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Moderator: General Moderators
Johnlbuk
Forum Newbie
Posts: 19 Joined: Mon Sep 10, 2007 3:01 pm
Post
by Johnlbuk » Fri Feb 01, 2008 12:13 pm
Hi,
I am trying to display a array as a table.
The code to create the array
Code: Select all
<?php $query = "SELECT name FROM table";
$result=mysql_query($query);
while($data = mysql_fetch_array($result)) {
$name = $data["name"];
$price= $data["price"];
$rowarray = array($name,$price);
}
?>
I then want to display the results of the array in this following form
Column 1 Column 2
row1 Name Price
row2 Name Price
row3 Name Price
etc
Any shread of the light would be great.
Cheers,
John
JAM
DevNet Resident
Posts: 2101 Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:
Post
by JAM » Fri Feb 01, 2008 12:53 pm
You could echo the contents in the while-loop directly instead of creating another array with the data, but...
Use a foreach() on $rowarray.
GuitarheadCA
Forum Newbie
Posts: 20 Joined: Fri Jul 13, 2007 12:59 am
Post
by GuitarheadCA » Sat Feb 02, 2008 2:24 am
$name = $data["name"];
$price= $data["price"];
$rowarray = array($name,$price);
It seems to me this round of assignments just makes things more complicated. Why not populate the table directly with the fetched array? it might look something like this:
Code: Select all
<?php
$query = "SELECT name, price FROM table";
$result=mysql_query($query);
echo '<table>'
$i = 1;
while($data = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td>row' . $i . '</td>';
echo '<td>' . $data['name'] . '</td>';
echo '<td>' . $data['price'] . '</td>';
echo '</tr>';
$i++;
}
?>
echo '</table>'
Johnlbuk
Forum Newbie
Posts: 19 Joined: Mon Sep 10, 2007 3:01 pm
Post
by Johnlbuk » Sun Feb 03, 2008 3:24 am
Yes. That would work using the fetch, but I need it to be in array as it is then going to be displayed on multiple pages. So I want to build the array and then, display it.
I am using this code to show the array now but it is only showing the name and then stopping so the price is not displayed. Any ideas?
Code: Select all
function show_array($array, $level, $sub){
if (is_array($array) == 1){ // check if input is an array
foreach($array as $key_val => $value) {
$offset = "";
if (is_array($value) == 1){ // array is multidimensional
echo "<tr>";
$offset = do_offset($level);
echo $offset . "<td>" . $key_val . "</td>";
show_array($value, $level+1, 1);
}
else{ // (sub)array is not multidim
if ($sub != 1){ // first entry for subarray
$offset = do_offset($level);
}
$sub = 0;
echo $offset . "<td>$value</td>";
}
} //foreach $array
}
else{ // argument $array is not an array
return;
}
}