Forum Moderators: coopster

Message Too Old, No Replies

'random' PHP queries and table layout

         

dave1236

3:28 am on Apr 20, 2008 (gmt 0)

10+ Year Member



All:

My latest challenge is to format my queries of my database. I am trying to get my layout straight. In short, I want to have my query results across 2 rows with 4 columns each.

Using this code, I get my results one row after another. I would like this code to provide my results, 1 result per column, with a total of 4 columns.

$query = "SELECT localimage, textlink,usercb FROM Stores WHERE status = 'active' ORDER BY rand() LIMIT 5";
$result = mysql_query($query)
or die ("Couldn't execute query-come on now!");

while ($row = mysql_fetch_array($result))
{
extract($row);
echo "
<tr>\n
<td>$localimage\n<br>
$usercb </td>\n
</td>\n

</tr>";
}
?>

Thanks for any input in helping me get my results go across a column, and not be a unique row.

Thanks again

IanKelley

4:09 am on Apr 20, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



If I understand what you're trying to do, something like this would work:


$cols = 4;
$cnt = 1;
while ($row = mysql_fetch_array($result))
{
extract($row);
if ($cnt == 1) echo "<tr>\n";
echo "<td>$localimage\n<br>$usercb</td>\n";
if ($cnt == $cols) { echo "</tr>\n"; $cnt = 0; }
$cnt++;
}
if ($cnt > 1) { $fill = $cols-$cnt+1; echo "<td colspan=\"$fill\"></td></tr>"; }

Above is off the top of my head, it's not tested and there's probably a better way to do it. The final IF statement fills in the missing columns and closes the row when the loop has ended without reaching 4 columns.

Also removed your second </td> as it looks like you were closing the same cell twice.

dave1236

6:40 pm on Apr 20, 2008 (gmt 0)

10+ Year Member



IanKelley:

Thanks much...it looks like it works exactly like I hoped.