Database records from MySQL to one array
How to place database records from the query in one array? If you’re using template engines such as Smarty you will have to assign an array to smarty variable if you want to use it in the template.
The easiest way is to create a function with the following procedure:
$res = @mysql_query ($query);
if ($res) {
for ($records = false;
$arrFetch = @mysql_fetch_array($res);
$records[] = $arrFetch);
@mysql_free_result($res);
}
if (is_array ($records))
reset ($records);
You will get an array called $records that will look something like this
$records = array (
0 => array (first record),
1 => array (second record...),
...
);
Of course, it can not be used for UPDATE, DELETE… only for SELECT, SHOW, DESCRIBE…
You can assign $records as smarty template variable:
$smarty->assign ('database_records', $records);
Even better, if you are not going to fetch more records to the same variable $records, you can use function assign_by_ref(). This is used to assign values to the templates by reference instead of making a copy. If you assign a variable by reference then change its value, the assigned value sees the change as well. For objects, assign_by_ref() also avoids an in-memory copy of the assigned object. See the PHP manual on variable referencing for an in-depth explanation.
$smarty->assign_by_ref ('database_records', $records);