Home >> FAQs/Tutorials >> MySQL Tutorials

MySQL Tutorial - Looping through Query Output Rows

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 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";
  $res = mysql_query($sql, $con);
  while ($row = mysql_fetch_assoc($res)) {
    print($row['id'].",".$row['url'].",".$row['time']."\n");
  }
  mysql_free_result($res);

  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-07-01 22:29:02
102, dba.fyicenter.com, 2006-07-01 22:29:02
1101, dev.fyicenter.com, 2006-07-01 22:29:02
1102, dba.fyicenter.com, 2006-07-01 22:29:02

Don't forget to call mysql_free_result($res). It is important to free up result set objects as soon as you are done with them.

(Continued on next topic...)

  1. How To Create a New Table?
  2. How To Get the Number of Rows Selected or Affected by a SQL Statement?
  3. How To Insert Data into an Existing Table?
  4. How To Fix the INSERT Command Denied Error?
  5. How To Insert Multiple Rows with a SELECT Statement?
  6. What Is a Result Set Object?
  7. How To Query Tables and Loop through the Returning Rows?
  8. How To Break Query Output into Pages?
  9. How To Update Existing Rows in a Table?
  10. How To Delete Existing Rows in a Table?
  11. How To Quote Text Values in SQL Statements?
  12. How To Quote Date and Time Values in SQL Statements?
  13. How To Display a Past Time in Days, Hours and Minutes?
  14. How To Perform Key Word Search in Tables?
  15. How To Build WHERE Criteria with Web Form Search Fields?
  16. How To Query Multiple Tables Jointly?
  17. How To Define the ID Column as Auto-Incremented?
  18. How To Get the Last ID Assigned by MySQL?

MySQL Tutorials:

More...


Other Tutorials/FAQs:

More...


Related Resources:

More...


Selected Jobs:

More...