I am aware of 3 different methods for accessing data with php/mysql, eg to print of all the IDs from a table:
All this code has not been checked, just typed in, it may have syntax/typing errors etc, but the concept remains.
Precode:
mysql_connect("host", "username", "password");
mysql_select_db("database");
$query = "SELECT * FROM table";
$results = mysql_query($query);
$row = mysql_fetch_assoc($results);
$numrows = mysql_num_rows($results);
First method, direct accessing of the record data and assigning to an intermittent variable:
for ($i = 0; $i < $numrows; i++) {
$varID = mysql_result($results,$i,'ID');
echo $varID;
}
Second method, getting an array of the data by use of an internal pointer on the mysql server which has to be reset once data is fetched:
do {
echo $row['ID'];
} while ($row = mysql_fetch_assoc($results));
if ($numrows > 0) {
mysql_data_seek($results, 0);
$row = mysql_fetch_assoc($results);
}
Third method, pulling the data once from the server into an array which can be used throughout the program:
for ($i = 0; $i < $numrows; i++) {
$records[$i] = $row;
$row = mysql_fetch_assoc($results);
}
foreach ($records as $key => $val) {
echo $val['ID'];
}
At the moment I use the first method since it allows easy usage of multiple tables with same field names and a simple easy to remember variable that can be used in the html, eg: say we have two tables, 'names', 'pizzas' and they both have an 'ID' field which for whatever reason we want to link the tables using a 'SELECT FROM pizzas, names *', we can differentiate data by doing as so:
$varNameID = mysql_result($results,$i,"names.ID");
$varPizzaID = mysql_result($results,$i,"pizzas.ID");
However, wouldn't the array (3rd) method be more efficient since the data is only fetched from the server once, and then can be used locally without connecting to the server again? Is the first or second method the prefered one by experts and which is faster/more efficitent?
Also I am not aware of how to do the above trick with the Pizzas and Names using the second method, is that at all possible?
Thanks a lot for reading this. Any feedback is greatly appreciated.