note 58483 deleted from function.mysql-query by philip

From: Date: Fri, 04 Sep 2015 19:20:25 +0000
Subject: note 58483 deleted from function.mysql-query by philip
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-203647@lists.php.net to get a copy of this message
Note Submitter: hipsurgery at gmail dot com ---- 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!

« previous php.notes (#203647) next »