user3497497
user3497497

Reputation: 13

Selecting from my database

Can anyone tell me why this code does not output all of the table info, only one name and email is displayed, and there are more than 1 in the table

<?
 $user_result = "select * from mytable;";
$qry = mysql_query($user_result) OR die(mysql_error());
$user_array = mysql_fetch_assoc($qry);


echo "<center>";
echo "<table CELLPADDING=10 border =1 >";
echo "<tr>";
echo  "<td>".$user_array['email']."</td>";
echo "<td>".$user_array['firstname']."</td>";

echo "</tr>";
echo "</table>";

mysql_close();
?>

Upvotes: 0

Views: 47

Answers (3)

Funk Forty Niner
Funk Forty Niner

Reputation: 74216

(Seems as I was putting this together, other answers have been given; submitting anyway)

You need to use a loop. I'm using a while loop in the example below.

<?
$user_result = "select * from mytable;";
$qry = mysql_query($user_result) OR die(mysql_error());

   echo "<center>"; // these are deprecated btw. Use CSS
   echo "<table CELLPADDING=10 border =1 >";

   echo "<tr> <th>Email</th> <th>Name</th></tr>"; // added as column headers

while($user_array = mysql_fetch_array($qry))
 {

   echo "<tr>";
   echo  "<td>".$user_array['email']."</td>";
   echo "<td>".$user_array['firstname']."</td>";
   echo "</tr>";

}

   echo "</table>";
   echo "</center>"; // these are deprecated btw

mysql_close();
?>

Footnotes:

mysql_* functions deprecation notice:

http://www.php.net/manual/en/intro.mysql.php

This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.

These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.

Documentation for MySQL can be found at » http://dev.mysql.com/doc/.

Upvotes: 1

Jim Grady
Jim Grady

Reputation: 210

As some of the comments mentioned, you would need to loop through the result like this.

<?
$query = "select * from mytable";
$user_result = mysql_query($query) OR die(mysql_error());

echo "<center>";
echo "<table>";

while ($user_array = mysql_fetch_assoc($user_result)) {
    echo "<tr>";
    echo "<td>" . $user_array['email'] . "</td>";
    echo "<td>" . $user_array['firstname'] . "</td>";
    echo "</tr>";
}

echo "</table>";
echo "</center>";

mysql_close();
?>

(I also switched around your variable names to avoid confusion between the query and the result of the query)

Upvotes: 1

Parag Tyagi
Parag Tyagi

Reputation: 8960

Use a while loop -

echo "<center>";
echo "<table CELLPADDING=10 border =1 >";

while($user_array = mysql_fetch_assoc($qry))
{
     echo "<tr>"; 
     echo  "<td>".$user_array['email']."</td>";
     echo "<td>".$user_array['firstname']."</td>";
     echo "</tr>";
}

echo "</table>";
echo "</center>";

Upvotes: 1

Related Questions