While Loop using PHP with a MySQL server

62,875

Solution 1

mysql_fetch_array() only retrieves a single row from the database. You need to call it inside your while loop to retrieve all rows. The $looping increment is unnecessary here, since mysql_fetch_array() returns false when no more rows are available.

while ($row = mysql_fetch_array($result))  
{
    echo $row["Name"].", Room ".$row["Room"].", Tel ".$row["Telephone"] ;
}

Solution 2

I'll do...

while ($row = mysql_fetch_assoc($result)) {
   // print $row;
}

Solution 3

while ($row = mysql_fetch_array($result))  
    {
        echo $row["Name"].", Room ".$row["Room"].", Tel ".$row["Telephone"] ;
    }
Share:
62,875
Chrisosaurus
Author by

Chrisosaurus

Scotland. I enjoy playing games I study at the University of Abertay in Dundee

Updated on July 21, 2022

Comments

  • Chrisosaurus
    Chrisosaurus almost 2 years

    I have a database (SQL) with the table "Staff" with two records in it. I am required to display the contents of these records on a web page using PHP.

    <html>
    <head>
    <title>CES Staff details</title>
    </head>
    
    <body>
    
    **code emitted**
    
    <?php
    $row = mysql_fetch_array($result) ; 
    $looping = 1;
    $i = $row.length;
    while ($looping <= $i)  
        {
            echo $row["Name"].", Room ".$row["Room"].", Tel ".$row["Telephone"] ;
            $looping++;
        }
    ?>
    </body>
    </html>
    

    How would I change the while loop correctly so that it will display both records on the page.

    Thanks!

  • Ravi Hirani
    Ravi Hirani about 8 years
    mysql and mysqli both are different. You are correct if he was using mysqli instead of mysql :)
  • Nosajimiki
    Nosajimiki over 4 years
    NOTE: 'mysql_fetch_array' was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. PHP 5.x is also deprecated; so, this method should no longer be used.