简体   繁体   English

MySQL-从表中获取列名并显示它们(使用PHP)

[英]MySQL - Get column names from table and display them (using PHP)

I want to take the column names from a table and display them, so i can compare them later. 我想从表中获取列名称并显示它们,以便稍后进行比较。 To get the names, i tried: 为了得到名字,我尝试了:

$entry = mysqli_query($con, 'SHOW COLUMNS FROM  table');

and

$entry = mysqli_query($con, "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '$db' AND TABLE_NAME = 'table'");

I don't know whether this runs correctly or not, since i don't get an error message there. 我不知道它是否正确运行,因为我在那里没有收到错误消息。 If i try to print the contents of $entry via echo, i keep getting errors. 如果我尝试通过echo打印$ entry的内容,我会不断出错。 Previously in my code, i print other entries using: 以前在我的代码中,我使用以下命令打印其他条目:

$test = mysqli_query($con, 'SELECT DISTINCT LK_Release FROM table');
while($row = mysqli_fetch_object($test))
{
echo "Releasename: " . "$row->LK_Release". "<br>";
... }

This output works for me. 此输出对我有用。 What i tried to output the columnnames: 我试图输出的列名:

while($row = mysqli_fetch_object($entry))
{
echo $row;
}

Any ideas? 有任何想法吗?

The following SQL statements are nearly equivalent: 以下SQL语句几乎等效:

 SELECT COLUMN_NAME
 FROM INFORMATION_SCHEMA.COLUMNS
 WHERE table_name = 'tbl_name'

You can use DESCRIBE: 您可以使用DESCRIBE:

DESCRIBE my_table;

Or in newer versions you can use INFORMATION_SCHEMA: 或者,在较新的版本中,您可以使用INFORMATION_SCHEMA:

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND    TABLE_NAME = 'my_table';

Or you can use SHOW COLUMNS: 或者,您可以使用SHOW COLUMNS:

SHOW COLUMNS FROM my_table;

Your query is already correct. 您的查询已经正确。 But you lack something in the fetching: 但是您在获取时缺少一些东西:

while($row = mysqli_fetch_object($entry))
{
    echo $row->Field . '<br/>';
              // ^ access the objects properties
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM