是否有一种方法可以在MySQL中使用PHP获取表的列名?


当前回答

Mysqli fetch_field()为我工作:

if ($result = $mysqli -> query($sql)) {
  // Get field information for all fields
  while ($fieldinfo = $result -> fetch_field()) {
    printf("Name: %s\n", $fieldinfo -> name);
    printf("Table: %s\n", $fieldinfo -> table);
    printf("Max. Len: %d\n", $fieldinfo -> max_length);
  }
  $result -> free_result();
}

来源:https://www.w3schools.com/pHP/func_mysqli_fetch_field.asp

其他回答

调查:

mysql_query('DESCRIBE '.$table);

我需要列名作为平面数组,而其他答案返回关联数组,所以我使用:

$con = mysqli_connect('localhost',$db_user,$db_pw,$db_name);
$table = 'people';

/**
* Get the column names for a mysql table
**/

function get_column_names($con, $table) {
  $sql = 'DESCRIBE '.$table;
  $result = mysqli_query($con, $sql);

  $rows = array();
  while($row = mysqli_fetch_assoc($result)) {
    $rows[] = $row['Field'];
  }

  return $rows;
}

$col_names = function get_column_names($con, $table);

$col_names现在等于:

(
    [0] => name
    [1] => parent
    [2] => number
    [3] => chart_id
    [4] => type
    [5] => id
)

你可能还想检查mysql_fetch_array(),如下所示:

$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
//$row[0] = 'First Field';
//$row['first_field'] = 'First Field';
}
$col = $db->query("SHOW COLUMNS FROM category");

while ($fildss = $col->fetch_array())
{             
    $filds[] = '"{'.$fildss['Field'].'}"';
    $values[] = '$rows->'.$fildss['Field'].'';
}

if($type == 'value')
{
    return $values = implode(',', $values);
}
else {
     return $filds = implode(',', $filds);
}

这个解决方案来自命令行mysql

mysql>USE information_schema;

在下面的查询中,只需将<——DATABASE_NAME——>更改为您的数据库,<——TABLENAME——>更改为您的表名,其中您只需要description语句的字段值

mysql> SELECT COLUMN_NAME FROM COLUMNS WHERE TABLE_SCHEMA = '<--DATABASE_NAME-->' AND   TABLE_NAME='<--TABLENAME-->';