Forum Moderators: open

Message Too Old, No Replies

Print query results using loop

         

cookie2

10:07 pm on May 2, 2006 (gmt 0)

10+ Year Member



I know that to loop through php arrays and print them out, this will work:

foreach($_POST as $key => $value){

if (is_array($value)) {
echo "$key = ";
foreach ($value as $a) {
echo "<i>$a, </i>";
}
echo "<br>";
}else{
echo "$key = $value<br>";
}
}

Is there a way to do this same thing with mysql query results? I have it hard coded right now using:

$query = ("SELECT * FROM `table`)");
$result = mysql_query($query);
$row = mysql_fetch_array($result);

print mysql_field_name($result, 0) . ": " . $row[ID]."<br>";
print mysql_field_name($result, 1) . ": " . $row[name]."<br>";
print mysql_field_name($result, 2) . ": " . $row[address]."<br>";
print mysql_field_name($result, 3) . ": " . $row[city]."<br>";

etc. but I'd like to be able to do it using a loop if possible and I just can't come up with one that will work. Can anyone help?

henry0

11:23 am on May 3, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Something like that:

<?
$sql= "select * from aaaaaa where username='$username' ";
$result = mysql_query($sql,$conn);
$num=mysql_numrows($result);
mysql_close();
$i=0;
while ($i <$num)
{
$id= mysql_result($result,$i,"id");
$nnnnnn= mysql_result($result,$i,"nnnnnn");

++$i;
}

?>

coopster

12:02 pm on May 3, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



$rows = mysql_query("SELECT * FROM table"); 
$list = '';
$count = 0;
$ri = false; // Reverse Image (alternate row shading)
while ($row = mysql_fetch_assoc($rows)) {
// Column Headings:
if (++$count == 1) {
$list .= '<tr class="ri">';
foreach($row as $key => $value) {
$list .= '<td>'.htmlentities($key)."</td>\n";
}
$list .= "</tr>\n";
}
$list .= '<tr' . (($ri) ? ' class="ri"' : '') . '>';
foreach($row as $value) {
$list .= '<td>'.htmlentities($value)."</td>\n";
}
$list .= "</tr>\n";
$ri = !$ri;
}

This snippet initializes some variables including a Reverse Image class indicator which you can <style> to make the rows alternating colors. Then upon the first iteration it will print the column headings once followed by every row of details. Works for any query of any size result set without any modifications. Enjoy.