note 108848 added to function.mysql-fetch-field

From: Date: Wed, 30 May 2012 10:20:04 +0000
Subject: note 108848 added to function.mysql-fetch-field
Groups: php.notes 
Request: Send a blank email to php-notes+get-188290@lists.php.net to get a copy of this message
Using mysql_fetch_field you can produce a more robust version of mysql_fetch_assoc. When querying 2 tables with the same field names, generally you would need to use mysql_fetch_row to get an integer key'ed array rather than an associated key'ed array. This is because fields of the same name in the second table will over-write the data returned from the first table. However this simple function will insert the table name prior to the field name for the key and prevent cross-overs. ie SELECT *, 'test' AS test 4 FROM table AS T_1, table AS T_2 WHERE T_1.a=T_2.b could produce: mysql_fetch_assoc() returns array( 'index'=>2, 'a'=>'pear', 'b'=>'apple', 'test'=>'test', 4=>4 ) mysql_fetch_table_assoc() returns array( 'T_1.index' =>1, 'T_1.a'=>'apple', 'T_1.b'=>'banana', 'T_2.index'=>2, 'T_2.a'=>'pear', 'T_2.b'=>'apple', 'test'=>'test', 4=>4 ) function mysql_fetch_table_assoc($resource) { // function to get all data from a query, without over-writing the same field // by using the table name and the field name as the index // get data first $data=mysql_fetch_row($resource); if(!$data) return $data; // end of data // get field info $fields=array(); $index=0; $num_fields=mysql_num_fields($resource); while($index<$num_fields) { $meta=mysql_fetch_field($resource, $index); if(!$meta) { // if no field info then just use index number by default $fields[$index]=$index; } else { $fields[$index]=''; // deal with field aliases - ie no table name (SELECT T_1.a AS temp) if(!empty($meta->table)) $fields[$index]=$meta->table.'.'; // deal with raw data - ie no field name (SELECT 1) if(!empty($meta->name)) $fields[$index].=$meta->name; else $fields[$index].=$index; } $index++; } $assoc_data=array_combine($fields, $data); return $assoc_data; } ---- Server IP: 69.147.83.197 Probable Submitter: 81.144.235.82 ---- Manual Page -- http://www.php.net/manual/en/function.mysql-fetch-field.php Edit -- https://master.php.net/note/edit/108848 Del: integrated -- https://master.php.net/note/delete/108848/integrated Del: useless -- https://master.php.net/note/delete/108848/useless Del: bad code -- https://master.php.net/note/delete/108848/bad+code Del: spam -- https://master.php.net/note/delete/108848/spam Del: non-english -- https://master.php.net/note/delete/108848/non-english Del: in docs -- https://master.php.net/note/delete/108848/in+docs Del: other reasons-- https://master.php.net/note/delete/108848 Reject -- https://master.php.net/note/reject/108848 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#188290) next »