Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through database and show in table

Tags:

php

mysql

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

like image 227
Elliott Avatar asked Jul 18 '26 00:07

Elliott


2 Answers

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>";
like image 75
Paul Dixon Avatar answered Jul 19 '26 13:07

Paul Dixon


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.

like image 23
Parrots Avatar answered Jul 19 '26 12:07

Parrots



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!