note 92328 added to function.mysql-fetch-array

From: Date: Mon, 20 Jul 2009 07:44:29 +0000
Subject: note 92328 added to function.mysql-fetch-array
Groups: php.notes 
Request: Send a blank email to php-notes+get-158492@lists.php.net to get a copy of this message
For all of you having problems accessing duplicated field names in queries with their table alias i have implemented the following quick solution: <?php function mysql_fetch_alias_array($result) { if (!($row = mysql_fetch_array($result))) { return null; } $assoc = Array(); $rowCount = mysql_num_fields($result); for ($idx = 0; $idx < $rowCount; $idx++) { $table = mysql_field_table($result, $idx); $field = mysql_field_name($result, $idx); $assoc["$table.$field"] = $row[$idx]; } return $assoc; } ?> Lets asume we have 2 tables student and contact each having fID as the index field and want to access both fID fields in php. The usage of this function will be pretty similar to calling mysql_fetch_array: <?php $result = mysql_query("select * from student s inner join contact c on c.fID = s.frContactID"); while ($row = mysql_fetch_alias_array($result)) { echo "StudenID: {$row['s.fID']}, ContactID: {$row['c.fID']}"; } ?> Voila, that's it :) Please be aware that by using this function, you have to access all fields with their alias name (e.g. s.Name, s.Birhtday) even if they are not duplicated. If you have questions, just send me a mail. Best regards, Mehdi Haresi die-webdesigner.at ---- Server IP: 69.147.83.197 Probable Submitter: 193.83.240.3 ---- Manual Page -- http://www.php.net/manual/en/function.mysql-fetch-array.php Edit -- https://master.php.net/note/edit/92328 Del: integrated -- https://master.php.net/note/delete/92328/integrated Del: useless -- https://master.php.net/note/delete/92328/useless Del: bad code -- https://master.php.net/note/delete/92328/bad+code Del: spam -- https://master.php.net/note/delete/92328/spam Del: non-english -- https://master.php.net/note/delete/92328/non-english Del: in docs -- https://master.php.net/note/delete/92328/in+docs Del: other reasons-- https://master.php.net/note/delete/92328 Reject -- https://master.php.net/note/reject/92328 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#158492) next »