View Full Version : Display Data without While Loop

11-17-2007, 12:24 AM
Can data in the database be displayed without using a while loop. Obviously only one record will get displayed.

mysql_select_db("db", $con);

$result = mysql_query("SELECT * FROM details");

while($row = mysql_fetch_array($result))
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";

11-17-2007, 12:38 AM
Short answer: Yes.

Long answer:
Yes. Just use the condition of the while loop as a statement. The reason why that assignment statement works is because mysql_fetch_array() returns FALSE when there are no more rows to read. If there are rows to read, then it returns the necessary information, making it TRUE. It is a fast way to write:

while (TRUE) {
$row = mysql_fetch_array($result);
if (!$row)
//rest of code

All you need to do is remove the while part:

$row = mysql_fetch_array($result);
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";

The reason why you see a while loop is because people usually have more than one, and in order to get to the desired one, the mysql_fetch_array() function must get called over and over.