I\'d like to get all of a mysql table\'s col names into an array in php?
Is there a query for this?
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
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; }
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')
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();
IN WORDPRESS:
global $wpdb; $table_name=$wpdb->prefix.'posts';
foreach ( $wpdb->get_col( "DESC " . $table_name, 0 ) as $column_name ) {
var_dump( $column_name );
}
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.