是否有一种方法可以在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);

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

$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
//$row[0] = 'First Field';
//$row['first_field'] = 'First Field';
}

我写了一个简单的php脚本,通过php获取表列: Show_table_columns.php

<?php
$db = 'Database'; //Database name
$host = 'Database_host'; //Hostname or Server ip
$user = 'USER'; //Database user
$pass = 'Password'; //Database user password
$con = mysql_connect($host, $user, $pass);
if ($con) {
    $link = mysql_select_db($db) or die("no database") . mysql_error();
    $count = 0;
    if ($link) {
        $sql = "
            SELECT column_name
            FROM   information_schema.columns
            WHERE  table_schema = '$db'
                   AND table_name = 'table_name'"; // Change the table_name your own table name
        $result = mysql_query($sql, $con);
        if (mysql_query($sql, $con)) {
            echo $sql . "<br> <br>";
            while ($row = mysql_fetch_row($result)) {
                echo "COLUMN " . ++$count . ": {$row[0]}<br>";
                $table_name = $row[0];
            }
            echo "<br>Total No. of COLUMNS: " . $count;
        } else {
            echo "Error in query.";
        }
    } else {
        echo "Database not found.";
    }
} else {
    echo "Connection Failed.";
}
?>

享受吧!

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函数 描述表 应该把你带到你想去的地方(把你的表名输入“table”)。您必须对输出进行一些解析,但这非常简单。我记得,如果执行该查询,PHP查询结果访问函数将以列名作为键,该函数通常会提供一个键-值对。但我已经有一段时间没有使用PHP了,所以不要强迫我这么做。:)