note 52806 added to function.mysql-fetch-array

From: Date: Fri, 13 May 2005 05:31:41 +0000
Subject: note 52806 added to function.mysql-fetch-array
Groups: php.notes 
Request: Send a blank email to php-notes+get-89361@lists.php.net to get a copy of this message
Regarding duplicated field names in queries, I wanted some way to retrieve rows without having to use alias, so I wrote this class that returns rows as 2d-arrays <? $field = $drow['table']['column']; ?> Here is the code: <? class mysql_resultset { var $results, $map; function mysql_resultset($results) { $this->results = $results; $this->map = array(); $index = 0; while ($column = mysql_fetch_field($results)) { $this->map[$index++] = array($column->table, $column->name); } } function fetch() { if ($row = mysql_fetch_row($this->results)) { $drow = array(); foreach ($row as $index => $field) { list($table, $column) = $this->map[$index]; $drow[$table][$column] = $row[$index]; } return $drow; } else return false; } } ?> The class is initialized with a mysql_query result: <? $resultset = new mysql_resultset(mysql_query($sql)); ?> The constructor builds an array that maps each field index to a ($table, $column) array so we can use mysql_fetch_row and access field values by index in the fetch() method. This method then uses the map to build up the 2d-array. An example: <? $sql = "select orders.*, clients.*, productos.* ". "from orders, clients, products ". "where join conditions"; $resultset = new mysql_resultset(mysql_query($sql)); while ($drow = $resultset->fetch()) { echo 'No.: '.$drow['orders']['number'].'<br>'; echo 'Client: '.$drow['clients']['name'].'<br>'; echo 'Product: '.$drow['products']['name'].'<br>'; } ?> I hope others find this useful as it has been to me. ---- Manual Page -- http://www.php.net/manual/en/function.mysql-fetch-array.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+52806 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+52806&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+52806&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+52806&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+52806&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+52806&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+52806&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#89361) next »