Jan 19 2010

PHP to get enum/set values from mysql field

Category: MySql,PhpGiulio Pons @ 10:36 am

This function returns an array with the elements allowed in a ENUM or SET mysql field. This can be usefull if you’re making some automation and need to retrieve those values without writing them in your code:

function set_and_enum_values( $table , $field ){
	$query = "SHOW COLUMNS FROM `$table` LIKE '$field'";
	$result = mysql_query( $query ) or die( 'Error getting Enum/Set field ' . mysql_error() );
	$row = mysql_fetch_array($result);
	if(stripos(".".$row[1],"enum(") > 0) $row[1]=str_replace("enum('","",$row[1]);
		else $row[1]=str_replace("set('","",$row[1]);
	$row[1]=str_replace("','","\n",$row[1]);
	$row[1]=str_replace("')","",$row[1]);
	$ar = split("\n",$row[1]);
	for ($i=0;$i<count($ar);$i++) $arOut[str_replace("''","'",$ar[$i])]=str_replace("''","'",$ar[$i]);
	return $arOut ;
}
  • Share/Bookmark

Related posts:

  1. 10 PHP usefull functions for MySQL stuff
  2. 10 PHP usefull functions for MySQLi stuff (mysql improved)
  3. MYSQL add counter in a query
  4. Execute Scalar and Execute Row for Php
  5. PHP function to fix collation on database fields of MySQL

4 Responses to “PHP to get enum/set values from mysql field”

  1. Giulio Pons’ Blog: PHP to get enum/set values from mysql field | Development Blog With Code Updates : Developercast.com says:

    [...] Pons has a quick post with a code snippet showing how to grab the possible values for an ENUM or SET field on a MySQL [...]

  2. Giulio Pons’ Blog: PHP to get enum/set values from mysql field | Webs Developer says:

    [...] Pons has a quick post with a code snippet showing how to grab the possible values for an ENUM or SET field on a MySQL [...]

  3. SeanJA says:

    You might be wanting to escape those variables… you know, so someone doesn’t try to get the enum of bobby’; DROP TABLE users;

  4. admin says:

    Sure, you have to use those function with trusted data.

Leave a Reply