MySQL query to get column names?

前端 未结 21 2142
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 01:56

I\'d like to get all of a mysql table\'s col names into an array in php?

Is there a query for this?

相关标签:
21条回答
  • 2020-11-22 02:41

    Edit: Today I learned the better way of doing this. Please see ircmaxell's answer.


    Parse the output of SHOW COLUMNS FROM table;

    Here's more about it here: http://dev.mysql.com/doc/refman/5.0/en/show-columns.html

    0 讨论(0)
  • 2020-11-22 02:41

    An old PHP function "mysql_list_fields()" is deprecated. So, today the best way to get names of fields is a query "SHOW COLUMNS FROM table_name [LIKE 'name']". So, here is a little example:

    $fields = array();
    $res=mysql_query("SHOW COLUMNS FROM mytable");
    while ($x = mysql_fetch_assoc($res)){
      $fields[] = $x['Field'];
    }
    foreach ($fields as $f) { echo "<br>Field name: ".$f; }
    
    0 讨论(0)
  • 2020-11-22 02:41

    I have tried this query in SQL Server and this worked for me :

    SELECT name FROM sys.columns WHERE OBJECT_ID = OBJECT_ID('table_name')
    
    0 讨论(0)
  • 2020-11-22 02:43
    function get_col_names(){  
        $sql = "SHOW COLUMNS FROM tableName";  
        $result = mysql_query($sql);     
        while($record = mysql_fetch_array($result)){  
         $fields[] = $record['0'];  
        }
        foreach ($fields as $value){  
          echo 'column name is : '.$value.'-';  
    }  
     }  
    
    return get_col_names();
    
    0 讨论(0)
  • 2020-11-22 02:43

    IN WORDPRESS:

    global $wpdb;   $table_name=$wpdb->prefix.'posts';
    foreach ( $wpdb->get_col( "DESC " . $table_name, 0 ) as $column_name ) {
      var_dump( $column_name );
    }
    
    0 讨论(0)
  • 2020-11-22 02:44

    This query fetches a list of all columns in a database without having to specify a table name. It returns a list of only column names:

    SELECT COLUMN_NAME
      FROM INFORMATION_SCHEMA.COLUMNS
      WHERE table_schema = 'db_name'
    

    However, when I ran this query in phpmyadmin, it displayed a series of errors. Nonetheless, it worked. So use it with caution.

    0 讨论(0)
提交回复
热议问题