Tuesday, April 27, 2010

PHP/MySQL records per row

Way to have the records pulled from a mysql database display like this in a table:
record1 | record2
record3 | record4
I am going to assume you know what you are talking about when you say “records”, and that you don’t really mean “fields”. If you really mean “fields” you can adapt the code below to suit your needs.
If you use mysql_fetch_array(), you will find out that $row is an array that is twice the length of the number of fields you selected. Why is that? Because mysql_fetch_array() returns both a numerical array and an associative array so that you can use either numbers or field names as the array key. If you use mysql_fetch_row(), the array $row will be a numerical array the same length as the number of fields you selected, which will be more convenient in this case because you need to numerically loop through the fields of the record you selected, then stop when all the fields have been echoed.
If you want to print out two records per row in the table, you can use the modulus operator(%) to start new rows. The modulus operator returns the remainder after integer division. Just keep count of the number of records you have echoed, and if the number is evenly divisible by 2($record_count % 2 == 0), then start a new row.
<table>
<
tr>
<?
php
$record_count
= 0; //Keeps count of the records echoed.
while ($row=mysql_fetch_row($sql_result))
{
//Check to see if it is time to start a new row
//Note: the first time through when
//$record_count==0, don't start a new row
if ($record_count % 2==0 AND $record_count != 0)
{
echo
'</tr><tr>';
}
echo ‘<td>’;
//Echo out the entire record in one table cell:
for ($i=0; $i< count($row); $i++)
{
echo
$row[$i];
}
echo ‘</td>’;
//Indicate another record has been echoed:
$record_count++;
}
?>
</tr>
</table>

No comments:

Post a Comment

 

Followers