note 75060 deleted from function.mysql-fetch-assoc by mazzanet
| From: | mazzanet@php.net | Date: | Sun, 27 May 2007 09:33:30 +0000 |
| Subject: | note 75060 deleted from function.mysql-fetch-assoc by mazzanet | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-126945@lists.php.net to get a copy of this message | ||
Note Submitter: frans at reijnhoudt dot nl
----
In the section "Return Values" it says
"If two or more columns of the result have the same field names, the last column will take
precedence. To access the other column(s) of the same name, you either need to access the result
with numeric indices by using mysql_fetch_row() or add alias names."
Adding alias names in MySQL isn't easy, because you can't ask for
SELECT table1.otherfield AS table1otherfield, * FROM table1 LEFT JOIN table2 ON
table1.somefield=table2.somefield
You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version
for the right syntax to use near '* FROM table1 LEFT JOIN table2 ON
table1.somefield=table2.somefield
And accessing the result with numeric indices by using mysql_fetch_row() has to be combined with
mysql_fetch_field to be really useful.
Suppose you have table1 with columns id, somefield and otherfield and table2 with id, somefield,
yetanotherfield. Then the result will be an associative array with keys 'table1.id',
'table1.somefield', 'otherfield', 'table2.id',
'table2.somefield', 'yetanotherfield'. So, if there are duplicate field names,
then the field name is prefixed with the table name and a dot.
<?php
function mysql_fetch_assoc_improved($result) {
$row = mysql_fetch_row($result);
if (!$row)
return $row;
$record = array();
$first_fields = array();
for ($i = 0; $i < mysql_num_fields($result); $i++) {
$field = mysql_fetch_field($result, $i);
if (isset($first_fields[$field->name])) { //this is not the first field with this name
$otherfield = $first_fields[$field->name];
if ($otherfield != null) { //correct the first field with this name
$record[$otherfield->table.'.'.$otherfield->name] =
$record[$otherfield->name];
unset($record[$otherfield->name]);
$first_fields[$field->name] = null;
}
$record[$field->table.'.'.$field->name] = $row[$i];
} else {
$record[$field->name] = $row[$i];
$first_fields[$field->name] = $field;
}
}
return $record;
}
?>