Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Banned
    Join Date
    Oct 2007
    Posts
    52
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Display Data without While Loop

    Can data in the database be displayed without using a while loop. Obviously only one record will get displayed.

    Code:
    mysql_select_db("db", $con);
    
    $result = mysql_query("SELECT * FROM details");
    
    while($row = mysql_fetch_array($result))
    {
      echo $row['FirstName'] . " " . $row['LastName'];
      echo "<br />";
    }

  • #2
    Regular Coder
    Join Date
    Mar 2005
    Location
    D0u$h!t3 k4?
    Posts
    512
    Thanks
    2
    Thanked 5 Times in 5 Posts
    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:
    Code:
    while (TRUE) {
    $row = mysql_fetch_array($result);
    if (!$row)
        break;
    //rest of code
    }
    All you need to do is remove the while part:
    Code:
    $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.
    PHP Code:
    $hello file_get_contents('hello.txt'); echo $hello
    hello


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •