tags:

views:

273

answers:

4

Hi, I am trying to loop though my users database to show each username in the table in their own row. I can only get it to show one user but loops through this the number of rows there are. Code is below

<?php
require_once ('../login/connection.php');
include ('functions.php');

$query = "SELECT * FROM users";
$results=mysql_query($query);
$row_count=mysql_num_rows($results);
$row_users = mysql_fetch_array($results);

echo "<table>";
    for ($i=0; $i<$row_count; $i++)
    {
    echo "<table><tr><td>".($row_users['email'])."</td></tr>";
    }
    echo "</table>";
?>

Thanks

A: 

Your problem is in this line:

echo "<table><tr><td>".($row_users['email'])."</td></tr>";

You're echoing out a <table> tag again. Remove that so your code looks like this:

echo "<table>";
    for ($i=0; $i<$row_count; $i++)
    {
    echo "<tr><td>".($row_users['email'])."</td></tr>";
    }
echo "</table>";
Marc W
+8  A: 

mysql_fetch_array fetches a single row - you typically use it in a while loop to eat all the rows in the result set, e.g.

echo "<table>";

while ($row_users = mysql_fetch_array($results)) {
    //output a row here
    echo "<tr><td>".($row_users['email'])."</td></tr>";
}

echo "</table>";
Paul Dixon
Thanks got it working now :)
Elliott
+3  A: 

You're only fetching one row:

$row_users = mysql_fetch_array($results);

You're never calling a fetch again so you're not really looping through anything.

I'd suggest changing your loop to the following:

echo "<table>";
while ($row = mysql_fetch_array($results)) {
    echo "<tr><td>".($row['email'])."</td></tr>";
}
echo "</table>";

The while loop will loop through the results and assign a row to $row, until you run out of rows. Plus no need to deal with getting the count of results at that point. This is the "usual" way to loop through results from a DB in php.

Parrots
A: 

You don't need to output a table within a table the way you're doing it.

$result = mysql_query("SELECT `email` FROM `users`");
$num_emails = mysql_num_rows($result);

echo "<table><caption>There are/is $num_emails email(s)</caption>";
while ($row = mysql_fetch_assoc($result)) {
    echo "<tr><td>{$row['email']}</td></tr>";
}
echo '</table>';

Something like that should work.

Nick Presta