Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index

PHP Tutorials - Looping through Returning Rows from a Query

By: FYICenter.com

(Continued from previous topic...)

How To Query Tables and Loop through the Returning Rows?

The best way to query tables and loop through the returning rows is to run the SELECT statement with the catch the mysql_query() function, catch the returning object as a result set, and loop through the result with the mysql_fetch_assoc() function in a while loop as shown in the following sample PHP script:

<?php
  include "mysql_connection.php";

  $sql = "SELECT id, url, time FROM fyi_links";
  $rs = mysql_query($sql, $con);
  while ($row = mysql_fetch_assoc($rs)) {
    print($row['id'].", ".$row['url'].", ".$row['time']."\n");
  }
  mysql_free_result($rs);

  mysql_close($con); 
?>

Using mysql_fetch_assoc() is better than other fetch functions, because it allows you to access field values by field names. If you run this script, you will see all rows from the fyi_links table are printed on the screen:

101, dev.fyicenter.com, 2006-02-26 22:29:02
102, dba.fyicenter.com, 2006-02-26 22:29:02
1101, dev.fyicenter.com, 2006-02-26 22:29:02
1102, dba.fyicenter.com, 2006-02-26 22:29:02

(Continued on next topic...)

  1. How To Install MySQL Server?
  2. How To Use MySQL Command Line Interface?
  3. What Do You Need to Connect PHP to MySQL?
  4. How To Connect to MySQL from a PHP Script?
  5. How To Create a Database?
  6. How To Select an Exiting Database?
  7. How To Run a SQL Statement?
  8. How To Create a Table?
  9. How To Get the Number of Rows Selected or Affected by a SQL Statement?
  10. How To Insert Data into a Table?
  11. How To Insert Rows Based on SELECT Statements?
  12. What Is a Result Set Object?
  13. How To Query Tables and Loop through the Returning Rows?
  14. How To Update Existing Rows in a Table?
  15. How To Delete Existing Rows in a Table?
  16. How To Quote Text Values in SQL Statements?
  17. How To Quote Date and Time Values in SQL Statements?
  18. How To Perform Key Word Search in Tables?
  19. How To Query Multiple Tables Jointly?
  20. How To Set the ID Column as Auto-Incremented?
  21. How To Get the Last ID Assigned by MySQL?

Selected Developer Jobs:

More...