note 58483 added to function.mysql-query

From: Date: Sat, 05 Nov 2005 18:30:07 +0000
Subject: note 58483 added to function.mysql-query
Groups: php.notes 
Request: Send a blank email to php-notes+get-98134@lists.php.net to get a copy of this message
This function will take the contents of any MySQL table, given only the table name, and return it as an index / associative multi-dimensional array in the form of: $array[$row_number][$column_name] = $value; I've found this very useful when you don't want to parse the table's contents in to HTML tags during a mysql_fetch_array() iteration. <?php function db_to_array($table_name) { $cols = array(); $x=0; $this_row=0; mysql_connect(HOST,USERNAME,PASSWORD); @mysql_select_db(DATABASE) or die( "Unable to select database"); $result_all=mysql_query("SELECT * FROM $table_name"); $result_cols = mysql_query("SHOW COLUMNS FROM $table_name"); mysql_close(); $numfields = mysql_num_fields($result_all); for($i=0;$i<mysql_num_rows($result_cols);$i++) { $cols[] = mysql_result($result_cols, $i); } while ($data = mysql_fetch_assoc($result_all)) { if ($x<$numfields) { $x++; } else { $x = 0; $this_row++; } foreach ($cols as $col_name) { $array[$this_row][$col_name] = $data[$col_name]; } mysql_data_seek($result_all, $this_row); } return $array; } // Test the function... $test_array = db_to_array("shows"); foreach ($test_array as $outer_key => $single_array) { foreach ($single_array as $inner_key => $value) { echo "\$test_array[$outer_key][$inner_key] = $value<br />"; } } ?> I'm just a hobbyist, so feel free to comment on my code or (worse!) tell me that there's some native PHP function that already does this! ---- Manual Page -- http://www.php.net/manual/en/function.mysql-query.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+58483 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+58483&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+58483&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+58483&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+58483&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+58483&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+58483&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+58483&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+58483&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#98134) next »