Scroll through the database and show in the table

I am trying to create a loop while my user database is to show each username in the table on its own row. I can get it to show only one user, but through that number of lines. Code 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

+1


a source to share


5 answers


mysql_fetch_array fetches one row - you usually use it in a while loop to eat all the rows in the result set, for example



echo "<table>";

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

echo "</table>";

      

+13


a source


You are only fetching one line:

$row_users = mysql_fetch_array($results);

      

You never call the fetch again, so you are not really looping anything.



I 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 the row ends. Plus there is no need to deal with getting the count of results at this point. This is the "normal" way of cycling results from database to php.

+4


a source


In new MYSQLI I am using 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);

      

+3


a source


Your problem is this line:

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

      

You are repeating the tag again <table>

. Remove this 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>";

      

0


a source


You don't need to dump the table inside the table the way you do 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 this should work.

0


a source







All Articles