Is there a way to grab the columns name of a table in MySQL using PHP?
You can use DESCRIBE:
DESCRIBE my_table;
Or in newer versions you can use INFORMATION_SCHEMA:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
Or you can use SHOW COLUMNS:
SHOW COLUMNS FROM my_table;
Or to get column names with comma in a line:
SELECT group_concat(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
The following SQL statements are nearly equivalent:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
[AND table_schema = 'db_name']
[AND column_name LIKE 'wild']
SHOW COLUMNS
FROM tbl_name
[FROM db_name]
[LIKE 'wild']
Reference: INFORMATION_SCHEMA COLUMNS
I made a PDO function which returns all the column names in an simple array.
public function getColumnNames($table){
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table";
try {
$core = Core::getInstance();
$stmt = $core->dbh->prepare($sql);
$stmt->bindValue(':table', $table, PDO::PARAM_STR);
$stmt->execute();
$output = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$output[] = $row['COLUMN_NAME'];
}
return $output;
}
catch(PDOException $pe) {
trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
}
}
The output will be an array:
Array (
[0] => id
[1] => name
[2] => email
[3] => shoe_size
[4] => likes
... )
Sorry for the necro but I like my function ;)
P.S. I have not included the class Core but you can use your own class.. D.S.
There's also this if you prefer:
mysql_query('SHOW COLUMNS FROM tableName');
This solution is from command line mysql
mysql>USE information_schema;
In below query just change <--DATABASE_NAME--> to your database and <--TABLENAME--> to your table name where you just want Field values of DESCRIBE statement
mysql> SELECT COLUMN_NAME FROM COLUMNS WHERE TABLE_SCHEMA = '<--DATABASE_NAME-->' AND TABLE_NAME='<--TABLENAME-->';
I needed column names as a flat array, while the other answers returned associative arrays, so I used:
$con = mysqli_connect('localhost',$db_user,$db_pw,$db_name);
$table = 'people';
/**
* Get the column names for a mysql table
**/
function get_column_names($con, $table) {
$sql = 'DESCRIBE '.$table;
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row['Field'];
}
return $rows;
}
$col_names = function get_column_names($con, $table);
$col_names now equals:
(
[0] => name
[1] => parent
[2] => number
[3] => chart_id
[4] => type
[5] => id
)
It's also interesting to note that you can use
EXPLAIN table_name which is synonymous with DESCRIBE table_name and SHOW COLUMNS FROM table_name
although EXPLAIN is more commonly used to obtain information about the query execution plan.
How about this:
SELECT #cCommand := GROUP_CONCAT( COLUMN_NAME ORDER BY column_name SEPARATOR ',\n')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
SET #cCommand = CONCAT( 'SELECT ', #cCommand, ' from my_database.my_table;');
PREPARE xCommand from #cCommand;
EXECUTE xCommand;
Look into:
mysql_query('DESCRIBE '.$table);
The MySQL function
describe table
should get you where you want to go (put your table name in for "table"). You'll have to parse the output some, but it's pretty easy. As I recall, if you execute that query, the PHP query result accessing functions that would normally give you a key-value pair will have the column names as the keys. But it's been a while since I used PHP so don't hold me to that. :)
The mysql_list_fields function might interest you ; but, as the manual states :
This function is deprecated. It is
preferable to use mysql_query() to
issue a SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead.
You may also want to check out mysql_fetch_array(), as in:
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
//$row[0] = 'First Field';
//$row['first_field'] = 'First Field';
}
in mysql to get columns details and table structure by following keywords or queries
1.DESC table_name
2.DESCRIBE table_name
3.SHOW COLUMNS FROM table_name
4.SHOW create table table_name;
5.EXPLAIN table_name
you can get the entire table structure using following simple command.
DESC TableName
or you can use following query.
SHOW COLUMNS FROM TableName
$col = $db->query("SHOW COLUMNS FROM category");
while ($fildss = $col->fetch_array())
{
$filds[] = '"{'.$fildss['Field'].'}"';
$values[] = '$rows->'.$fildss['Field'].'';
}
if($type == 'value')
{
return $values = implode(',', $values);
}
else {
return $filds = implode(',', $filds);
}
this worked for me..
$sql = "desc MyTableName";
$result = #mysql_query($sql);
while($row = #mysql_fetch_array($result)){
echo $row[0]."<br>";
}
I have write a simple php script to fetch table columns through PHP:
Show_table_columns.php
<?php
$db = 'Database'; //Database name
$host = 'Database_host'; //Hostname or Server ip
$user = 'USER'; //Database user
$pass = 'Password'; //Database user password
$con = mysql_connect($host, $user, $pass);
if ($con) {
$link = mysql_select_db($db) or die("no database") . mysql_error();
$count = 0;
if ($link) {
$sql = "
SELECT column_name
FROM information_schema.columns
WHERE table_schema = '$db'
AND table_name = 'table_name'"; // Change the table_name your own table name
$result = mysql_query($sql, $con);
if (mysql_query($sql, $con)) {
echo $sql . "<br> <br>";
while ($row = mysql_fetch_row($result)) {
echo "COLUMN " . ++$count . ": {$row[0]}<br>";
$table_name = $row[0];
}
echo "<br>Total No. of COLUMNS: " . $count;
} else {
echo "Error in query.";
}
} else {
echo "Database not found.";
}
} else {
echo "Connection Failed.";
}
?>
Enjoy!
mysqli fetch_field() worked for me:
if ($result = $mysqli -> query($sql)) {
// Get field information for all fields
while ($fieldinfo = $result -> fetch_field()) {
printf("Name: %s\n", $fieldinfo -> name);
printf("Table: %s\n", $fieldinfo -> table);
printf("Max. Len: %d\n", $fieldinfo -> max_length);
}
$result -> free_result();
}
Source: https://www.w3schools.com/pHP/func_mysqli_fetch_field.asp
The easy way, if loading results using assoc is to do this:
$sql = "SELECT p.* FROM (SELECT 1) as dummy LEFT JOIN `product_table` p on null";
$q = $this->db->query($sql);
$column_names = array_keys($q->row);
This you load a single result using this query, you get an array with the table column names as keys and null as value.
E.g.
Array(
'product_id' => null,
'sku' => null,
'price' => null,
...
)
after which you can easily get the table column names using the php function array_keys($result)
Related
I want to select records from two tables. These two tables have the prefix "shop_".
How do I select the records for both shops in a sql statement?
My current statement:
// Select
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM database_name WHERE TABLE_NAME LIKE 'shop%'");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arr[] = $row;
}
$name = [];
foreach($arr as $arrs)
{
$name[] = array(0 => $arrs['name'], 1 => $arrs['html_id'], 2 => $arrs['price']); //here
}
$stmt->close();
print_r($name);
The mysql php current error is:
Fatal error: Uncaught Error: Call to a member function execute() on boolean in C:\wamp642\www\webcart\search.php on line 17 and line 17 is: $stmt->execute();
I can get the tables to "show" with this command:
$stmt = $mysqli->prepare("show tables like '%shop%'");
But it doesn't get the records, just an object I think.
The output of "show tables like '%shop%'" prints 2 arrays just like it should, but the arrays are empty with no data/records.
I'm thinking it's the sql statement that needs work. Thanks.
EDIT:
I've also tried:
$stmt = $mysqli->prepare("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='feeds' AND TABLE_NAME LIKE 'shop%'");
EDIT: The contents of search.php
<?php
include 'define.php';
$mysqli = new mysqli($host, $db_user, $db_password, $db_database);
if($mysqli->connect_error)
{
?><script>var profiles_delete_modal_1 = ' Error 3: Problem deleteing profile. Make sure database login credentials are correct.';</script>
<script>$(".modal").css({"opacity":"1", "z-index":"100"});$(".modal_mid").html("<pre>" + profiles_delete_modal_1 + "</pre>");setTimeout(function(){$(".modal").css({"opacity":"0", "z-index":"-100"});},5000);</script><?php
exit;
}
$shop = 'shop';
// Select
//$stmt = $mysqli->prepare("show tables like '%shop%'");
//$stmt = $mysqli->prepare("SELECT * FROM feeds WHERE TABLE_NAME LIKE 'shop%'");
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM database_name WHERE TABLE_NAME LIKE 'shop%'");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arr[] = $row;
}
$n=0;
$name = [];
foreach($arr as $arrs)
{
$name[] = array(0 => $arrs['name'], 1 => $arrs['html_id'], 2 => $arrs['price']); //here
$n++;
}
$stmt->close();
print_r($name);
and the contents of define.php:
$www_dir = 'webcart';
$url_root = 'http://localhost/' . $www_dir . '';
$www_dir_slash = $_SERVER['DOCUMENT_ROOT'] . '' . $www_dir . '/';
$host = 'localhost';
$db_user = 'webcart_admin';
$db_password = 'asd123';
$db_database = 'shop';
$_SESSION['host'] = $host;
$_SESSION['db_user'] = $db_user;
$_SESSION['db_password'] = $db_password;
$_SESSION['db_database'] = $db_database;
EDIT
From going on the answer stated below I've been able to create a string like this:
SELECT name, html_id, price FROM shop_a UNION shop_b
however it won't execute properly.
This is my code:
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM shop_a UNION shop_b");
$result = $stmt->execute();
It gives the following error:
Fatal error: Uncaught Error: Call to a member function execute() on boolean in C:\wamp642\www\webcart\search.php on line 43
EDIT Got it.
I'll post the answer up soon. The statement goes like this:
"SELECT name, html_id, price FROM shop_a UNION SELECT name, html_id, price from shop_b"
I got the answer pretty much from musafar, although I needed to get to the objects in the array. So I used some foreach loops to do this seeing as I don't know any other way. If there's another way to get to mysqli_object data, please let me know.
$stmt = $mysqli->prepare("SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = 'shop' AND table_name LIKE 'shop%'");
//table_schema is the database name and 'shop%' is the search string
$stmt->execute();
$tables = $stmt->get_result();
$stmt->close();
$arr = [];
foreach($tables as $tabless)
{
$arr[] = $tabless;
}
foreach($arr as $arrs)
{
$toby[] = implode(',',$arrs);
}
$tobyy = implode(' UNION SELECT name, html_id, price from ',$toby);
//$tobyy = "shop_a UNION SELECT name, html_id, price from shop_b"
$arr = [];
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM " . $tobyy);
$result = $stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arr[] = $row;
}
$n=0;
$name = [];
foreach($arr as $arrs)
{
$name[$n] = array(0 => $arrs['name'], 1 => $arrs['html_id'], 2 => $arrs['price']); //here
$n++;
}
$stmt->close();
print_r($name);
//$name = "Array ( [0] => Array ( [0] => Chromecast [1] => chromecast [2] => 59 ) [1] => Array ( [0] => EZCast [1] => ezcast [2] => 49 ) )"
SELECT query is used to fetch data from DB tables, not DB itself. So you need to provide a table name in the FROM part of your query.
Considering you're trying to fetch data from similar tables (same fields)...
$stmt = $mysqli->prepare("SELECT table_name FROM information_schema.tables WHERE table_schema = 'wp_105424' AND table_name LIKE 'shop%'");
$stmt->execute();
$tables = $stmt->get_result();
$dataStmt = $mysqli->prepare("SELECT name, html_id, price FROM " . implode(',', $tables)); // name, html_id, price should be in all tables that starts with *shop*
$dataStmt->execute();
$data = $dataStmt->get_result();
And you may need to add conditions to handle all scenarios.
The follwing shows how to output an individual table column comment.
$db = mysql_connect("localhost","root","xyz") or die(mysql_error());
mysql_select_db("database",$db) or die(mysql_error());
function table_description($t,$c,$d){
$sql = "SELECT column_comment FROM information_schema.columns
WHERE table_name = '$t' AND column_name LIKE '$c'";
$query = mysql_query($sql,$d) or die(mysql_error());
$v = mysql_fetch_row($query);
if($v){
return $v[0];
}
return 'Table description not found';
}
echo table_description('table','col',$db);
However I would like table_description to return an array of every column comment in that table.
e.g. Column_Name, Column_Comments (so "RecID" => "ID of the record") etc.
I have little experience of working with php arrays/ converting resultsets to array.
loop through the query results with a while loop, store the results in an array outside of the scope of the while loop...
for example:
function table_description($t,$c,$d){
$t = mysql_real_escape_string($t); //prevent sql injection
$c = mysql_real_escape_string($c);
$sql = "SELECT column_comment,column_name FROM information_schema.columns
WHERE table_name = '$t' AND column_name LIKE '$c'";
$query = mysql_query($sql,$d) or die(mysql_error());
$columnArray = array();
while($result = mysql_fetch_array($query)){
$columnArray[] = array('column_comment' => $result['column_comment'], 'column_name' => $result['column_name']);
}
return $columnArray;
}
$columnArray[0]['column_name'] would return the column name of the first element of the array $columnArray
How can I get number of fields(сolumns) in mysql table with PHP or just some kind of mysql query? Is there a way to do this without SELECT * FROM table_name and mysql_num_fields()? Maybe there is a way with one mysql query?
SELECT COUNT(*) totalColumns
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table1' AND
TABLE_SCHEMA = 'databaseName'
SQLFiddle Demo
Use the below query to get no of fields in table,
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'database_name'
AND table_name = 'tbl_name'
#user1858864 All the above answers are fine but I just wanted to give it to you in php using pdo .
And I did up vote your question and their answers because everything seems to be relevant to me
A big thanks to #JW. For editing
<?php
try {
$con = new PDO('mysql:host=localhost;dbname=mydb;charset=utf-8','root','');
} catch(PDOException $e){
echo 'Connection failed'.$e->getMessage();
}
#count in pdo
$count = ("SELECT count(*) FROM table_name ");
$result =$con->prepare($count);
$result->execute();
$number= $result->fetchColumn();
echo $number;
#count in pdo
?>
$query = "select book_name from tbllibrary "; $result = mysql_query($query);
//while loop to display mysql table field values in html text boxes
$i = 0;
while ($row = mysql_fetch_row($result))
{
$count = count($row);
$y = 0;
while ($y < $count)
{
$c_row = current($row);
next($row);
$y = $y + 1;
}
$book_name=$c_row;$i = $i + 1;
}
echo 'There are ' . $i. ' books available in the Library</p>';
Here the variable i will store total no.of columns for the row named book_name. You can also use the variable $book name for the future use but it is not mandatory.
You can use the following query
SELECT count(*) FROM table_name
Hi guys i need help about displaying a column name of a specific table example i have a table named account and it has account_id, first_name, last_name and stuffs like that what i need is to display the account_id, first_name, last_name and so on and not the data inside that column really need your help.. thanks :)
SELECT table_name, column_name, data_type, data_length
FROM USER_TAB_COLUMNS
WHERE table_name = 'mydatabase'
that's the code i found while i was researching for answers but i don't know how to excecute this one.. i really have no idea how would i use this to display the column name..
$result = mysql_query("SHOW COLUMNS FROM sometable");
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
}
the result maybe:
Array
(
[Field] => id
[Type] => int(7)
[Null] =>
[Key] => PRI
[Default] =>
[Extra] => auto_increment
)
How about using DESCRIBE
DESCRIBE tablename;
Try it here: http://sqlfiddle.com/#!2/a2581/2823/0
i need is to display the account_id, first_name, last_name and so on and not the data inside that column
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'B'
SQLFiddle Demo
SELECT column_name FROM information_schema.COLUMNS WHERE TABLE_NAME='table';
This should take the columns right from the information schema.
It is recommended to use MySQLi over MySQL in terms of PHP.
You can use mysqli_fetch_field()
$query = "SELECT blah from blah ORDER BY blah 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();
}
$query= "SELECT table_name, column_name, data_type, data_length
FROM USER_TAB_COLUMNS
WHERE table_name = 'mytablename' ";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)) {echo "$row[acount_id] $row[first_name] $row[last_name]";}
Use the above to echo all three data from database
How can I check if mysql table field even exists ?
The column name is 'price' and I need to see if it exists.
Haven't understood really how the 'EXISTS' works...
Any examples or ideas ?
Thanks
In PHP:
$fields = mysql_list_fields('database_name', 'table_name');
$columns = mysql_num_fields($fields);
for ($i = 0; $i < $columns; $i++) {$field_array[] = mysql_field_name($fields, $i);}
if (!in_array('price', $field_array))
{
$result = mysql_query('ALTER TABLE table_name ADD price VARCHAR(10)');
}
This should also help you:
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ‘TEST’ AND COLUMN_NAME = ‘TEST_DATE’)
BEGIN
ALTER TABLE TEST ADD TEST_DATE DATETIME
END
Or you can do:
Show columns from table like 'string';
There has been a similar question posed on SO here before.
Try:
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TEST' AND COLUMN_NAME = 'Price')
BEGIN
-- do something, e.g.
-- ALTER TABLE TEST ADD PRICE DECIMAL
END
Another way of doing it in PHP:
$chkcol = mysql_query("SELECT * FROM `table_name` LIMIT 1");
$mycol = mysql_fetch_array($chkcol);
if(isset($mycol['price']))
echo "Column price exists! Do something...";
Well, one way is to do:
select price from your_table limit 1
If you get an error:
#1054 - Unknown column 'price' in 'field list'
then it does not exists.
I found this very useful. It will list all the tables that has that column name.
SELECT table_name,
column_name
FROM information_schema.columns
WHERE column_name LIKE '%the_column_name%'
well here is a function to check out if a particular column exists or not.
public function detect_column($my_db, $table, $column)
{
$db = mysql_select_db($my_db); //select the database
$sql = "SHOW COLUMNS FROM $table LIKE '$column'"; //query
$result = mysql_query($sql); //querying
if(mysql_num_rows($result) == 0) //checks the absence of column
echo "column $column doesn't exist !";
// write your code here!
else
echo "column $column exists!";
}
well if you are designing a frame work, then this function may come to your aid. This function checks for the presence of column when $flag is set to '1' and absence of column when $flag is set to '0'.
public function detect_column($my_db, $table, $column, $flag)
{
$this->select_db($my_db); //select the database
$sql = "SHOW COLUMNS FROM $table LIKE '$column'";
$result = mysql_query($sql);
if(mysql_num_rows($result) == $flag)
return true;
else
return false;
}
You could get a description of all the column in your table.
desc your_table;
I just done something like this using this function for Wordpress, this for update tables that having new chnages on it
public function alterTable() {
$table_name = $this->prefix . $this->tables['name'];
$select = "select * from `{$table_name}` where 0=0 limit 1;";
$query = $this->db->get_results($select, ARRAY_A);
if (isset($query[0]) && !key_exists('adv', $query[0])) {
$sql = "ALTER TABLE `{$table_name}` ADD `me` INT NULL DEFAULT NULL ;";
$this->db->query($sql);
}
}