2013-03-08 37 views
1

我在stackexchange上发布了下面的代码审查。但我只是意识到我所要求的可能是SO的合法问题。 如果您不这么认为,请让我知道。php脚本从sql表中检索枚举值

我有一个SQL表有多个字段,其中4个是枚举。我编写了一个脚本,它运行思想表并检索枚举并将它们放入2维数组中。

不幸的是,这个脚本速度很慢,我无法修复它。

<?php 

require_once('mySQL_Connect.php'); 

$con = ConnectToDataBase(); 
if ($con == false) 
{ 
    //data returned will be null 
    exit; 
} 

$db = 'courses_db'; 
$table = 'courses'; 

$fields = array(
'training_field', 
'speciality_field', 
'type', 
'language'); 

$enums = array(); 

foreach ($fields as $colomn) { 
$sq1 = "SELECT 
      column_type 
     FROM 
      information_schema.columns 
     WHERE 
      table_schema = '$db' 
     AND 
      table_name = '$table' 
     AND 
      column_name = '$colomn'"; 
$query = mysqli_query($con,$sq1); 

$stack = array(); 
$i = 0; 
$stack[$i]=$colomn; 
if ($fetch = mysqli_fetch_assoc($query)) 
{ 
    $enum = $fetch['column_type']; 
    $off = strpos($enum,"("); 
    $enum = substr($enum, $off+1, strlen($enum)-$off-2); 
    $values = explode(",",$enum); 

    // For each value in the array, remove the leading and trailing 
    // single quotes, convert two single quotes to one. Put the result 
    // back in the array in the same form as CodeCharge needs. 

    for($n = 0; $n < Count($values); $n++) { 
    $val = substr($values[$n], 1,strlen($values[$n])-2); 
    $val = str_replace("''","'",$val); 
    $stack[$i+1]=$val; 
    $i++; 
    } 
} 
    // return the values array to the caller 
    //echo json_encode($stack); 
    array_push($enums,$stack); 
    reset($stack); 
} 
echo json_encode($enums); 
?> 

回答

2

我终于找到了解决办法,在这里它(希望这将是有用的人):

function get_enum_values($connection, $table, $field) 
{ 

    $query = " SHOW COLUMNS FROM `$table` LIKE '$field' "; 
    $result = mysqli_query($connection, $query); 
    $row = mysqli_fetch_array($result , MYSQL_NUM); 
    #extract the values 
    #the values are enclosed in single quotes 
    #and separated by commas 
    $regex = "/'(.*?)'/"; 
    preg_match_all($regex , $row[1], $enum_array); 
    $enum_fields = $enum_array[1]; 

    return($enum_fields); 
} 

所以基本上没有必要去通过INFORMATION_SCHEMA!

幸得此博客:

http://akinas.com/pages/en/blog/mysql_enum/

0

由于CodeCharge在原来的问题被提及,存在Utilize MySQL Enum Field Type下CCS在线帮助的例子。示例代码与上述类似,但也可用多种语言提供。