PHP list function with mysql_query

When we want to output something from a mysql database we select, query it then use the mysql_fetch_array function to return an array that corresponds to the fetched row.
Most of us are using $row['rowname'] to extract desired info from that row but we can make use of list() function:
Example using $row['rowname']:

  1. $select = "SELECT * FROM users ORDER BY id ASC";
  2. $query = mysql_query($select);
  3. while($row = mysql_fetch_array($query)) {
  4.  echo "{$row['id']} {$row['name']} {$row['pass']}";
  5. }



Example using list() function
We assume that the users database has only 3 columns: id, name and pass.

  1. $select = "SELECT * FROM users ORDER BY id ASC ";
  2. $query = mysql_query($select);
  3. while(list($id, $name, $pass) = mysql_fetch_row($query)) {
  4.  echo $id . " " . $name . " " . $pass . "<br />";
  5. }

Basically list() function will put every element from an array obtained with mysql_fetch_row function in the variables $id (id column), $name (name column), $pass (pass column).

If the users database has more columns, for example datetime column but we don’t want to use it, then use list() like:
list($id, $name, $pass, ) – you notice that we’ve add a comma and an empty space to replace the variable.

No related php tutorials.

bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark
tabs-top

Leave a Reply