像在数组mysql中那样只获取列名 [英] Get Only column names as in array mysql

查看:121
本文介绍了像在数组mysql中那样只获取列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在php和mysql中都是新手.我想创建一个动态表,该表将包含mysql数据库中表的所有字段.我正在尝试获取数组中的所有列名称,但无法执行.我正在尝试以下代码:

I am new in both php and mysql. I want to create a dynamic table that will have all fields from table in mysql database. I am trying to get all column names in an array but fail to do. I am trying following code:

<?php
    $fields = mysql_query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'mytablename' ");
    $res = mysql_fetch_array($fields);
    foreach ($res as $field)
    {
        echo '<tr>';
        echo '<td>';
        echo $field;
        echo '</td>';
        echo '<td>';
        echo "<input type='text' class='' name='tags' id='tags' value=''>";
        echo '</td>';
        echo '</tr>';
    }
    ?>

任何帮助将不胜感激.

推荐答案

您不需要额外的SQL查询即可获取字段名称.您可以使用常规SELECT查询,只需从该查询中获取您的字段名称(和定义)即可.这样更好的性能!

You dont need an additional SQL query just to get your field names. You can use your normale SELECT query and just get your field names (and definition) from that query. Better performance this way!

不建议使用的MySQL解决方案:

不推荐使用MySQL库.可以在此链接中使用它,但是您应该切换到mysqli库,当按程序使用时,该库几乎相同(第二个示例).

The MySQL Library is deprecated. It can be used as in this link, btu you should switch to the mysqli Library which is nearly identical when used proceduraly (second sample).

htttp://www.php.net/manual/en/function.mysql-field-name.php

htttp://www.php.net/manual/en/function.mysql-field-name.php

OOP MySQLi解决方案:

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {
/* Get field information for all columns */
    while ($finfo = $result->fetch_field()) {
        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    $result->close();
}    

MySQLi程序解决方案:

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = mysqli_query($link, $query)) {
    /* Get field information for all fields */
    while ($finfo = mysqli_fetch_field($result)) {
        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    mysqli_free_result($result);
}

http://www.php.net/manual/zh_/mysqli-result.fetch-field.php

这篇关于像在数组mysql中那样只获取列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆