note 92069 added to function.mysql-fetch-field

From: Date: Tue, 07 Jul 2009 18:18:41 +0000
Subject: note 92069 added to function.mysql-fetch-field
Groups: php.notes 
Request: Send a blank email to php-notes+get-158029@lists.php.net to get a copy of this message
A nice function to return an array of all fields for a particular table. I've added a few very useful properties to the spec: 'len', which is supplied by the mysql_field_len() function. 'definition', which is a column_definition which could be used to initialize the table. 'auto_increment', which is 1 if the field is auto_increment. <?php function mysql_fetch_fields($table) { // LIMIT 1 means to only read rows before row 1 (0-indexed) $result = mysql_query("SELECT * FROM $table LIMIT 1"); $describe = mysql_query("SHOW COLUMNS FROM $table"); $num = mysql_num_fields($result); $output = array(); for ($i = 0; $i < $num; ++$i) { $field = mysql_fetch_field($result, $i); // Analyze 'extra' field $field->auto_increment = (strpos(mysql_result($describe, $i, 'Extra'), 'auto_increment') === FALSE ? 0 : 1); // Create the column_definition $field->definition = mysql_result($describe, $i, 'Type'); if ($field->not_null && !$field->primary_key) $field->definition .= ' NOT NULL'; if ($field->def) $field->definition .= " DEFAULT '" . mysql_real_escape_string($field->def) . "'"; if ($field->auto_increment) $field->definition .= ' AUTO_INCREMENT'; if ($key = mysql_result($describe, $i, 'Key')) { if ($field->primary_key) $field->definition .= ' PRIMARY KEY'; else $field->definition .= ' UNIQUE KEY'; } // Create the field length $field->len = mysql_field_len($result, $i); // Store the field into the output $output[$field->name] = $field; } return $output; } // Example: mysql_connect('localhost', 'user', 'pass'); mysql_select_db('database'); $fields = mysql_fetch_fields('table'); foreach ($fields as $key => $field) { echo $field->name . ' ' . $field->definition . "\n"; } // May output: // field1 char(8) // field2 int PRIMARY KEY // field3 int AUTO_INCREMENT UNIQUE KEY // field4 mediumtext NOT NULL DEFAULT 'I\'m a little teapot' ?> ---- Server IP: 208.69.120.35 Probable Submitter: 129.186.42.164 ---- Manual Page -- http://www.php.net/manual/en/function.mysql-fetch-field.php Edit -- https://master.php.net/note/edit/92069 Del: integrated -- https://master.php.net/note/delete/92069/integrated Del: useless -- https://master.php.net/note/delete/92069/useless Del: bad code -- https://master.php.net/note/delete/92069/bad+code Del: spam -- https://master.php.net/note/delete/92069/spam Del: non-english -- https://master.php.net/note/delete/92069/non-english Del: in docs -- https://master.php.net/note/delete/92069/in+docs Del: other reasons-- https://master.php.net/note/delete/92069 Reject -- https://master.php.net/note/reject/92069 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#158029) next »