0

下图显示了如何输出单个表格列的注释。

$db = mysql_connect("localhost","root","xyz") or die(mysql_error()); 
mysql_select_db("database",$db) or die(mysql_error()); 

function table_description($t,$c,$d){ 
     $sql = "SELECT column_comment FROM information_schema.columns  
      WHERE table_name = '$t' AND column_name LIKE '$c'"; 
     $query = mysql_query($sql,$d) or die(mysql_error()); 
     $v = mysql_fetch_row($query); 
     if($v){ 
         return $v[0]; 
         } 
     return 'Table description not found'; 
     } 

echo table_description('table','col',$db);  

但是,我希望 table_description 返回该表中每个列注释的数组。例如Column_Name,Column_Comments(所以“RecID”=>“记录的ID”)等。我没有使用php数组/将结果集转换为数组的经验。

4

1 回答 1

1

使用循环遍历查询结果while,将结果存储在循环范围之外的数组中while......

例如:

function table_description($t,$c,$d){
     $t = mysql_real_escape_string($t); //prevent sql injection
     $c = mysql_real_escape_string($c);

     $sql = "SELECT column_comment,column_name FROM information_schema.columns  
      WHERE table_name = '$t' AND column_name LIKE '$c'"; 
     $query = mysql_query($sql,$d) or die(mysql_error());
     $columnArray = array();

     while($result = mysql_fetch_array($query)){


       $columnArray[] = array('column_comment' => $result['column_comment'], 'column_name' => $result['column_name']);

     }

    return $columnArray;
}

$columnArray[0]['column_name']将返回数组 $columnArray 的第一个元素的列名

于 2013-08-22T18:37:02.393 回答