I\'d like to get all of a mysql table\'s col names into an array in php?
Is there a query for this?
The call of DESCRIBE
is working fine to get all columns of a table but if you need to filter on it, you need to use the SHOW COLUMNS FROM
instead.
Example of PHP function to get all info of a table :
// get table columns (or return false if table not found)
function get_table_columns($db, $table) {
global $pdo;
if($cols = $pdo->query("DESCRIBE `$db`.`$table`")) {
if($cols = $cols->fetchAll(PDO::FETCH_ASSOC)) {
return $cols;
}
}
return false;
}
In my case, I had to find the primary key of a table. So, I used :
SHOW COLUMNS FROM `table` WHERE `Key`='PRI';
Here is my PHP function :
// get table Primary Key
function get_table_pk($db, $table) {
global $pdo;
$q = "SHOW COLUMNS FROM `$db`.`$table` WHERE `Key` = 'PRI'";
if($cols = $pdo->query($q)) {
if($cols = $cols->fetchAll(PDO::FETCH_ASSOC)) {
return $cols[0];
}
}
return false;
}