What exactly are some various ways to loop via a mysql result set? I am a new comer to PHP and MySQL so I am searching for approaches to loop through as well as an explanation regarding the way the provided code works.

This is a full example:


  1. Connect
  2. Choose database
  3. Make query
  4. Cycle around the result and fetch array to obtain the row

If you work with MySQL versions 4.1.3 or later, it is strongly recommended that you employ the mysqli extension rather [from the mysql extension that's not further developed, doesn't support options that come with MySQL 4.1+, no prepared and multiple claims, doesn't have object-oriented interface, ...]

see mysqli-stmt.fetch for that procedural and object oriented methods to loop on the mysqli result set.

the very first example that involves my thoughts:


    $link = mysql_connect(/*arguments here*/);

    $query = sprintf("select * from table");

    $result = mysql_query($query, $link);

    if ($result) {
      while($row = mysql_fetch_array($result)) {
        // do something with the $row

    else {
      echo mysql_error();

I'd recommend developing a database function that functions like a wrapper for the database fetch. Causes it to be simpler to change out database function calls, as well as, in the future, the kind of database itself (e.g. mysql->postgresql or mysql->couchdb or while using PDO object or something like that).

Some function that -you- create that can take a question and returns a completely associative array, and you stick the database connection code inside there.

This may also be great to check on into using PDO in the future, because it abstracts away database specific functions for you personally, dealing with mysql, postgresql, etc.