What are some different ways to loop through a mysql result set? I'm new to PHP and MySQL so I'm looking for simple ways to loop through and an explanation as to how the provided code works.
Here is a full example:
http://php.net/manual/en/function.mysql-fetch-array.php
- Connect
- Select database
- Make query
- Cycle on the result and fetch array to get the row
the first example that comes to my mind:
<?php
$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 creating a database function that acts as a wrapper for your database fetch. Makes it easier to switch out database function calls, and even, down the road, the type of database itself (e.g. mysql->postgresql or mysql->couchdb or using the PDO object or something).
Some function that -you- create that takes a query and returns a fully associative array, and then you stick the database connection code inside there.
It may also be good to check into using PDO down the road, since it abstracts away database specific functions for you, working with mysql, postgresql, etc.
If you are using MySQL versions 4.1.3 or later, it is strongly recommended that you use the mysqli extension instead [of the mysql extension that is not further developed, does not support features of MySQL 4.1+, no prepared and multiple statements, has no object-oriented interface, ...]
see mysqli-stmt.fetch for the procedural and object oriented ways to loop over a mysqli result set.