I'm having a strange issue with putting a query into a html table to be displayed in a php/mysql set up. The query will always produce one more result than is shown. For example, if 1 set of results was returned, nothing would show in the table. If there are 5, only 4 get shown. I've tried the same queries with a pre-defined function to produce a table based on a query and it produced the right table with the correct number of results. Here is an example (apologies for the indenting, or lack thereof):
$user_id = implode($_SESSION['user_id']);
$query = "SELECT name, address
FROM user
WHERE user_id = '$user_id'
ORDER BY date_added DESC";
$result = mysql_query($query) or die ("query failed: " . mysql_error());
echo "<table border='1' style=\"border-collapse: collapse;\">
<tr style=\"background-color: #000066; color: #FFFFFF;\">
<th>Name</th>
<th>Address</th>
</tr>";
$rowCt = 0; // Row counter
while($row = mysql_fetch_array($result))
{
if($rowCt++ % 2 == 0) $Style = "background-color: #00CCCC;";
else $Style = "background-color: #0099CC;";
echo "<tr style=\"$Style\">";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "</tr>";
}
echo "</table>";
Any idea why this is happening? Any help would be greatly appreciated, it's been driving me crazy and need to figure it out before I can move on! Thanks.
EDIT
I've altered it slightly to loop through the amount of rows as that number is correct, and the table is now the correct size, however the last result is always empty. Any ideas?
$rowCt = 0; // Row counter
$i = 0;
echo mysql_num_rows($result). ' number of rows';
$num = mysql_num_rows($result);
//while($row = mysql_fetch_array($result))
while ($i < $num)
{
$row = mysql_fetch_array($result);
if($rowCt++ % 2 == 0) $Style = "background-color: #00CCCC;";
else $Style = "background-color: #0099CC;";
echo "<tr style=\"$Style\">";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "</tr>";
$i++;
}
echo "</table>";
Thanks
Try this.........
<style>
#s {
background-color: #000066;
color: #FFFFFF;
}
#s1 {
background-color: #0CC;
}
#s2 {
background-color: #09C;
}
</style>
<?php
$user_id = implode($_SESSION['user_id']);
$result = mysql_query("SELECT name, address FROM user WHERE user_id = '$user_id' ORDER BY date_added DESC", $your_connection) or die ("query failed: " . mysql_error());
?>
<table border="1" style="border-collapse:collapse;">
<tr id="s">
<th>Name</th>
<th>Address</th>
</tr>
<?php
$rowCt = 0; // Row counter
while($row = mysql_fetch_assoc($result))
{
if($rowCt++ % 2 == 0):
$Style = "s1";
else:
$Style = "s2";
endif;
?>
<tr id="<?php echo $Style; ?>">
<td><?php $row['name']; ?></td>
<td><?php $row['address']; ?></td>
</tr>
<?php } ?>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With