note 73755 deleted from function.mysql-query by philip

From: Date: Fri, 04 Sep 2015 19:19:28 +0000
Subject: note 73755 deleted from function.mysql-query by philip
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-203643@lists.php.net to get a copy of this message
Note Submitter: JustinB at harvest dot org ---- If you're looking to create a dynamic dropdown list or pull the possible values of an ENUM field for other reasons, here's a handy function: <?php // Function to Return All Possible ENUM Values for a Field function getEnumValues($table, $field) { $enum_array = array(); $query = 'SHOW COLUMNS FROM ' . $table . ' LIKE "' . $field . '"'; $result = mysql_query($query); $row = mysql_fetch_row($result); preg_match_all('/\'(.*?)\'/', $row[1], $enum_array); if(!empty($enum_array[1])) { // Shift array keys to match original enumerated index in MySQL (allows for use of index values instead of strings) foreach($enum_array[1] as $mkey => $mval) $enum_fields[$mkey+1] = $mval; return $enum_fields; } else return array(); // Return an empty array to avoid possible errors/warnings if array is passed to foreach() without first being checked with !empty(). } ?> This function asumes an existing MySQL connection and that desired DB is already selected. Since this function returns an array with the original enumerated index numbers, you can use these in any later UPDATEs or INSERTS in your script instead of having to deal with the string values. Also, since these are integers, you can typecast them as such using (int) when building your queries--which is much easer for SQL injection filtering than a string value.

« previous php.notes (#203643) next »