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 best way is to use the INFORMATION_SCHEMA metadata virtual database. Specifically the INFORMATION_SCHEMA.COLUMNS table...
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
AND `TABLE_NAME`='yourtablename';
It's VERY powerful, and can give you TONS of information without need to parse text (Such as column type, whether the column is nullable, max column size, character set, etc)...
Oh, and it's standard SQL (Whereas SHOW ... is a MySQL specific extension)...
For more information about the difference between SHOW... and using the INFORMATION_SCHEMA tables, check out the MySQL Documentation on INFORMATION_SCHEMA in general...
You can use the following query for MYSQL:
SHOW `columns` FROM `your-table`;
Below is the example code which shows How to implement above syntax in php to list the names of columns:
$sql = "SHOW COLUMNS FROM your-table";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)){
echo $row['Field']."<br>";
}
For Details about output of SHOW COLUMNS FROM TABLE visit: MySQL Refrence.
Seems there are 2 ways:
DESCRIBE `tablename`
or
SHOW COLUMNS FROM `tablename`
More on DESCRIBE here: http://dev.mysql.com/doc/refman/5.0/en/describe.html
I have done this in the past.
SELECT column_name
FROM information_schema.columns
WHERE table_name='insert table name here';
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
Use mysql_fetch_field() to view all column data. See manual.
$query = 'select * from myfield';
$result = mysql_query($query);
$i = 0;
while ($i < mysql_num_fields($result))
{
$fld = mysql_fetch_field($result, $i);
$myarray[]=$fld->name;
$i = $i + 1;
}
"Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future."
The simplest solution out of all Answers:
DESC `table name`
or
DESCRIBE `table name`
or
SHOW COLUMNS FROM `table name`
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; }
when you want to check your all table structure with some filed then use this code. In this query i select column_name,column_type and table_name for more details . I use order by column_type so i can see it easily.
SELECT `COLUMN_NAME`,COLUMN_TYPE,TABLE_NAME
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename' order by DATA_TYPE;
If you want to check only double type filed then you can do it easily
SELECT `COLUMN_NAME`,COLUMN_TYPE,TABLE_NAME,DATA_TYPE
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename' AND DATA_TYPE like '%bigint%' order by DATA_TYPE;
if you want to check which field allow null type etc then you can use this
SELECT `COLUMN_NAME`,COLUMN_TYPE,TABLE_NAME,IS_NULLABLE,DATA_TYPE
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename' and DATA_TYPE like '%bigint%' and IS_NULLABLE ='NO' order by COLUMN_TYPE;
you want to check more then thik link also help you.
https://dev.mysql.com/doc/refman/5.7/en/columns-table.html
this generates a string of column names with a comma delimiter:
SELECT CONCAT('(',GROUP_CONCAT(`COLUMN_NAME`),')')
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='database_name'
AND `TABLE_NAME`='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();
Not sure if this is what you were looking for, but this worked for me:
$query = query("DESC YourTable");
$col_names = array_column($query, 'Field');
That returns a simple array of the column names / variable names in your table or array as strings, which is what I needed to dynamically build MySQL queries. My frustration was that I simply don't know how to index arrays in PHP very well, so I wasn't sure what to do with the results from DESC or SHOW. Hope my answer is helpful to beginners like myself!
To check result: print_r($col_names);
SHOW COLUMNS in mysql 5.1 (not 5.5) uses a temporary disk table.
http://dev.mysql.com/doc/refman/5.1/en/internal-temporary-tables.html
http://dev.mysql.com/doc/refman/5.1/en/show-columns.html
So it can be considered slow for some cases. At least, it can bump up your created_tmp_disk_tables value. Imagine one temporary disk table per connection or per each page request.
SHOW COLUMNS is not really so slow, possibly because it uses file system cache. Phpmyadmin says ~0.5ms consistently. This is nothing compared to 500ms-1000ms of serving a wordpress page. But still, there are times it matters. There is a disk system involvement, you never know what happens when server is busy, cache is full, hdd is stalled etc.
Retrieving column names through SELECT * FROM ... LIMIT 1 was around ~0.1ms, and it can use query cache as well.
So here is my little optimized code to get column names from a table, without using show columns if possible:
function db_columns_ar($table)
{
//returns Array('col1name'=>'col1name','col2name'=>'col2name',...)
if(!$table) return Array();
if(!is_string($table)) return Array();
global $db_columns_ar_cache;
if(!empty($db_columns_ar_cache[$table]))
return $db_columns_ar_cache[$table];
//IMPORTANT show columns creates a temp disk table
$cols=Array();
$row=db_row_ar($q1="SELECT * FROM `$table` LIMIT 1");
if($row)
{
foreach($row as $name=>$val)
$cols[$name]=$name;
}
else
{
$coldata=db_rows($q2="SHOW COLUMNS FROM `$table`");
if($coldata)
foreach($coldata as $row)
$cols[$row->Field]=$row->Field;
}
$db_columns_ar_cache[$table]=$cols;
//debugexit($q1,$q2,$row,$coldata,$cols);
return $cols;
}
Notes:
As long as your tables first row does not contain megabyte range of data, it should work fine.
The function names db_rows and db_row_ar should be replaced with your specific database setup.
IN WORDPRESS:
global $wpdb; $table_name=$wpdb->prefix.'posts';
foreach ( $wpdb->get_col( "DESC " . $table_name, 0 ) as $column_name ) {
var_dump( $column_name );
}
Try this one out I personally use it:
SHOW COLUMNS FROM $table where field REGEXP 'stock_id|drug_name'
This question is old, but I got here looking for a way to find a given query its field names in a dynamic way (not necessarily only the fields of a table). And since people keep pointing this as the answer for that given task in other related questions, I'm sharing the way I found it can be done, using Gavin Simpson's tips:
//Function to generate a HTML table from a SQL query
function myTable($obConn,$sql)
{
$rsResult = mysqli_query($obConn, $sql) or die(mysqli_error($obConn));
if(mysqli_num_rows($rsResult)>0)
{
//We start with header. >>>Here we retrieve the field names<<<
echo "<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"0\"><tr align=\"center\" bgcolor=\"#CCCCCC\">";
$i = 0;
while ($i < mysqli_num_fields($rsResult)){
$field = mysqli_fetch_field_direct($rsResult, $i);
$fieldName=$field->name;
echo "<td><strong>$fieldName</strong></td>";
$i = $i + 1;
}
echo "</tr>";
//>>>Field names retrieved<<<
//We dump info
$bolWhite=true;
while ($row = mysqli_fetch_assoc($rsResult)) {
echo $bolWhite ? "<tr bgcolor=\"#CCCCCC\">" : "<tr bgcolor=\"#FFF\">";
$bolWhite=!$bolWhite;
foreach($row as $data) {
echo "<td>$data</td>";
}
echo "</tr>";
}
echo "</table>";
}
}
This can be easily modded to insert the field names in an array.
Using a simple: $sql="SELECT * FROM myTable LIMIT 1" can give you the fields of any table, without needing to use SHOW COLUMNS or any extra php module, if needed (removing the data dump part).
Hopefully this helps someone else.
if you use php, use this gist.
it can get select fields full info with no result,and all custom fields such as:
SELECT a.name aname, b.name bname, b.*
FROM table1 a LEFT JOIN table2 b
ON a.id = b.pid;
if above sql return no data,will also get the field names aname, bname, b's other field name
just two line:
$query_info = mysqli_query($link, $data_source);
$fetch_fields_result = $query_info->fetch_fields();
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.
if you only need the field names and types (perhaps for easy copy-pasting into Excel):
SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA='databasenamegoeshere'
AND DATA_TYPE='decimal' and TABLE_NAME = 'tablenamegoeshere'
remove
DATA_TYPE='decimal'
if you want all data types
i no expert, but this works for me..
$sql = "desc MyTable";
$result = #mysql_query($sql);
while($row = #mysql_fetch_array($result)){
echo $row[0]."<br>"; // returns the first column of array. in this case Field
// the below code will return a full array-> Field,Type,Null,Key,Default,Extra
// for ($c=0;$c<sizeof($row);$c++){echo #$row[$c]."<br>";}
}
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')
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;
}
I need to add a 'prefix' in front of every value in a certain column.
Example: all fields in column x are: 200, 201, 202, 203, etc.
I need them to be pn_200, pn_201, pn_202, pn_203, etc.
Is there a way to use ALTER or MODIFY commands to do this?
I would like something like ADD to BEGINNING of * column_name 'pn_'
Or perhaps a way to do it in PHP? Maybe get the value of the field, turn that into a variable, and do something like.
`$variablex = `'SELECT column_name FROM table'
$result = mysqli_query($con, variablex);
foreach($r=mysqli_fetch_row($result) {
`ADD TO BEGINNING OF * column_name 'pn_'`
Is there anyway to do that?
Actually it's even easier.
UPDATE table SET column_name = CONCAT('pn_', column_name)
Without a WHERE clause it will update all the rows of your table
SELECT concat('pn_', column_name) AS column_name
FROM yourtable
but why do this at the database layer? It's trivial to do it in PHP:
SELECT column_name ...
while($row = mysql_fetch_assoc($result)) {
$data = 'pn_' . $row['column_name'];
}
i think this is what you want
$que = "SELECT column_name FROM table";
$res = mysql_query($que, $con);
if(mysql_num_rows($res)>0){
while($row = mysql_fetch_array($res)){
echo "PN_". $row['column_name'];
}
}
if you only want to show it wit pn_ at the beginnning
but if you want to change it also in the database you need to select all get the id value and
update it with concatination
UPDATE MyTable
SET MyField = CONCAT('pn_', MyField)
I want to execute a SELECT query but I don't how many columns to select.
Like:
select name, family from persons;
How can I know which columns to select?
"I am currently designing a site for the execute query by users.
So when the user executes this query, I won't know which columns selected.
But when I want to show the results and draw a table for the user I should know which columns selected."
For unknown query fields, you can just use this code.
It gives you every row fields name=>data. You can even change the key to '' to get ordered array columns by num following the columns' order in the database.
$data = array();
while($row = mysql_fetch_assoc($query))
{
foreach($row as $key => $value) {
$data[$row['id']][$key] = $value;
}
}
print_r($data);
First, understand exactly what data you want to retrieve. Then look at the database schema to find out which tables the database contains, and which columns the tables contain.
The following query returns a result set of every column of every table in the database:
SELECT table_name, column_name
FROM INFORMATION_SCHEMA.COLUMNS;
In this sqlfiddle, it returns the following result set (truncated here for brevity):
TABLE_NAME COLUMN_NAME
-----------------------
CHARACTER_SETS CHARACTER_SET_NAME
CHARACTER_SETS DEFAULT_COLLATE_NAME
CHARACTER_SETS DESCRIPTION
CHARACTER_SETS MAXLEN
COLLATIONS COLLATION_NAME
COLLATIONS CHARACTER_SET_NAME
COLLATIONS ID
COLLATIONS IS_DEFAULT
COLLATIONS IS_COMPILED
COLLATIONS SORTLEN
Now I know that I can select the column CHARACTER_SET_NAME from the table CHARACTER_SETS like this:
SELECT CHARACTER_SET_NAME
FROM CHARACTER_SETS;
Use mysqli::query to execute these queries.
If I understand what you are asking, you probably want to use MySQLIi and the the fetch_fields method on the result set:
http://us3.php.net/manual/en/mysqli-result.fetch-fields.php
See the examples on that page.
If you want to get column names for any query in all cases it's not so easy.
In case at least one row is returned you can get columns directly from this row.
But when you want to get column names when there is no result to display table/export to CSV, you need to use PDO functions that are not 100% reliable.
// sample query - it might contain joins etc.
$query = 'select person.name, person.family, user.id from persons LEFT JOIN users ON persons.id = user.person_id';
$statement = $pdo->query($query);
$data = $statement->fetchAll(PDO::FETCH_CLASS);
if (isset($data[0])) {
// there is at least one row - we can grab columns from it
$columns = array_keys((array)$data[0]);
}
else {
// there are no results - no need to use PDO functions
$nr = $statement->columnCount();
for ($i = 0; $i < $nr; ++$i) {
$columns[] = $statement->getColumnMeta($i)['name'];
}
}
Use mysql_query() and execute this query:
SHOW COLUMNS FROM table
Example:
<?php
$result = mysql_query("SHOW COLUMNS FROM sometable");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
}
?>
use DESC table or
Example
SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_name='your_table';
output
column1,column2,column3
Use fetch_fields
$sql = "SELECT * FROM AT_EMPLOYEES;";
$result = mysqli_query($conn, $sql);
$finfo = $result->fetch_fields();
foreach ($finfo as $val) {
echo $val->name ."<br>";
}
I can't seem to find or write a sqlquery that SELECTS the DEFAULT VALUE
(and I don't think I can generate it in phpmyadmin for me to copy)
I tried to SELECT it as if it was a record but to no avail...
$defaultValue_find = mysql_query(
"SELECT $group FROM grouptable WHERE $group='DEFAULT'")
or die("Query failed:".mysql_error());
$defaultValue_fetch = mysql_fetch_row($defaultValue_find);
$defaultValue = $defaultValue_fetch[0];
echo $defaultValue;
"SELECT $group FROM grouptable WHERE $group=DEFAULT( $group ) "
Or I think better:
"SELECT DEFAULT( $group ) FROM grouptable LIMIT 1 "
Update - correction
As #Jeff Caron pointed, the above will only work if there is at least 1 row in grouptable. If you want the result even if the grouptable has no rows, you can use this:
"SELECT DEFAULT( $group )
FROM (SELECT 1) AS dummy
LEFT JOIN grouptable
ON True
LIMIT 1 ;"
Get the default values of all fields in mytable in the associative array $res:
// MySQL v.5.7+
$res = [];
$sql = "SHOW FULL COLUMNS FROM `mytable`";
foreach ($PDO->query( $sql, PDO::FETCH_ASSOC ) as $row) {
$res[$row['Field']] = $row['Default'] ;
}
print_r($res);
You can get the default column of any table, and in fact lots of interesting information about it, by looking at the INFORMATION_SCHEMA.COLUMNS tables. As the documentation states...
INFORMATION_SCHEMA provides access to database metadata, information about the MySQL server such as the name of a database or table, the data type of a column, or access privileges. (Source: MySQL 8.0 Reference Manual / INFORMATION_SCHEMA Tables / Introduction.)
So, to get the column default, just SELECT COLUMN_DEFAULT, like...
SELECT COLUMN_DEFAULT
FROM information_schema.columns
WHERE TABLE_SCHEMA = 'YourSchema'
AND TABLE_NAME = 'YourTable' AND
COLUMN_NAME = 'YourField';
You can then just wrap this into a subquery, SELECT * FROM YourTable WHERE YourField = (queryabove). This lets you make a much more customizable, default-based list in your MySQL query.
I am trying to add a column to my table before another column using BEFORE, I can't use AFTER because the column names before aren't a constant. This is what I have:
ALTER TABLE testfyf ADD intake_10_2013 VARCHAR(20) NOT NULL BEFORE url;
Everything up until BEFORE is working.
Before anyone says anything about this, I know adding columns this way is not a good idea, but it is what my boss wants.
Does anyone know how I can achieve this? I have found plenty of examples that say this should work but it doesn't.
MySQL (if this is mysql - you just tagged it sql generically) does not support a BEFORE keyword. You will have to find out the name of the previous column and add it with AFTER.
You can use this statement to list the column names and determine programmatically with PHP after which one your new one should be placed.
SHOW COLUMNS FROM tablename;
Here's a function that should return the column before 'url'. I didn't test it but I think it will do the job.
// Queries the table column information and returns the column name just before `url`
function get_column_before_url() {
$result = mysql_query("SHOW COLUMNS FROM testfyf");
while ($row = mysql_fetch_array($result)) {
if ($row['Field'] == "url") {
// you should clean up your mysql resources before returning
mysql_free_result($result);
return $lastcol;
}
// Store the column name to return if the next one turns out to be `url`
else $lastcol = $row['Field'];
}
}
Now you can do:
$column_before = get_column_before_url();
$sql = "ALTER TABLE testfyf ADD intake_10_2013 VARCHAR(20) NOT NULL AFTER $column_before;";
$result = mysql_query($sql);
if (!$result) echo $mysql_error();
You could use the information_schema to get the columns of the table in order:
SELECT c.COLUMN_NAME
, #n := #n + 1 AS column_id
FROM
( SELECT COLUMN_NAME
FROM information_schema.columns
WHERE TABLE_SCHEMA = 'yourDatabase'
AND TABLE_NAME = 'yourTable'
) AS c
CROSS JOIN
( SELECT #n := 0 ) AS v
If you join the above to itself, you could get the name of the previous column and use ADD COLUMN with AFTER.