How To Query Tables and Loop through the Returning Rows


How To Query Tables and Loop through the Returning Rows? - MySQL FAQs - Managing Tables and Running Queries with PHP Scripts



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:

  include "mysql_connection.php";

  $sql = "SELECT id, url, time FROM fyi_links";
  $res = mysql_query($sql, $con);
  while ($row = mysql_fetch_assoc($res)) {


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

2007-05-11, 5491👍, 0💬