Elliott
Elliott

Reputation: 3864

loop through database and show in table

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

Upvotes: 2

Views: 53174

Answers (5)

JerryB
JerryB

Reputation: 43

In the new MYSQLI, I use this coding

$query = "SELECT * FROM users";
$results=mysqli_query($con,$query);
$row_count=mysqli_num_rows($results);

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

mysqli_query($con,$query); 
mysqli_close($con);

Upvotes: 4

Nick Presta
Nick Presta

Reputation: 28675

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.

Upvotes: 0

Parrots
Parrots

Reputation: 26882

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.

Upvotes: 4

Paul Dixon
Paul Dixon

Reputation: 300855

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>";

Upvotes: 15

Marc W
Marc W

Reputation: 19241

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>";

Upvotes: 0

Related Questions