Related
How can I get all the column names from a table using PDO?
id name age
1 Alan 35
2 Alex 52
3 Amy 15
The info that I want to get are,
id name age
EDIT:
Here is my attempt,
$db = $connection->get_connection();
$select = $db->query('SELECT * FROM contacts');
$total_column = $select->columnCount();
var_dump($total_column);
for ($counter = 0; $counter < $total_column; $counter ++) {
$meta = $select->getColumnMeta($counter);
$column[] = $meta['name'];
}
print_r($column);
Then I get,
Array
(
[0] => id
[1] => name
[2] => age
...
)
I solve the problem the following way (MySQL only)
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
This will work for MySQL, Postgres, and probably any other PDO driver that uses the LIMIT clause.
Notice LIMIT 0 is added for improved performance:
$rs = $db->query('SELECT * FROM my_table LIMIT 0');
for ($i = 0; $i < $rs->columnCount(); $i++) {
$col = $rs->getColumnMeta($i);
$columns[] = $col['name'];
}
print_r($columns);
My 2 cents:
$result = $db->query('select * from table limit 1');
$fields = array_keys($result->fetch(PDO::FETCH_ASSOC));
And you will get the column names as an array in the var $fields.
$sql = "select column_name from
information_schema.columns where
table_name = 'myTable'";
PHP function
credits : http://www.sitepoint.com/forums/php-application-design-147/get-pdo-column-name-easy-way-559336.html
function getColumnNames()
{
$sql = "SELECT column_name FROM information_schema.columns WHERE table_name = 'myTable'";
#$sql = 'SHOW COLUMNS FROM ' . $this->table;
$stmt = $this->connection->prepare($sql);
try {
if ($stmt->execute())
{
$raw_column_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($raw_column_data as $outer_key => $array)
{
foreach($array as $inner_key => $value
{
if (!(int)$inner_key)
{
$this->column_names[] = $value;
}
}
}
}
return $this->column_names;
}
catch (Exception $e)
{
return $e->getMessage(); //return exception
}
}
Here is the function I use. Created based on #Lauer answer above and some other resources:
//Get Columns
function getColumns($tablenames) {
global $hostname , $dbnames, $username, $password;
try {
$condb = new PDO("mysql:host=$hostname;dbname=$dbnames", $username, $password);
//debug connection
$condb->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$condb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// get column names
$query = $condb->prepare("DESCRIBE $tablenames");
$query->execute();
$table_names = $query->fetchAll(PDO::FETCH_COLUMN);
return $table_names;
//Close connection
$condb = null;
} catch(PDOExcepetion $e) {
echo $e->getMessage();
}
}
Usage Example:
$columns = getColumns('name_of_table'); // OR getColumns($name_of_table); if you are using variable.
foreach($columns as $col) {
echo $col . '<br/>';
}
This is an old question but here's my input
function getColumns($dbhandle, $tableName) {
$columnsquery = $dbhandle->query("PRAGMA table_info($tableName)");
$columns = array();
foreach ($columnsquery as $k) {
$columns[] = $k['name'];
}
return $columns;
}
just put your variable for your pdo object and the tablename. Works for me
This approach works for me in SQLite and MySQL. It may work with others, please let me know your experience.
Works if rows are present
Works if no rows are present (test with DELETE FROM table)
Code:
$calendarDatabase = new \PDO('sqlite:calendar-of-tasks.db');
$statement = $calendarDatabase->query('SELECT *, COUNT(*) FROM data LIMIT 1');
$columns = array_keys($statement->fetch(PDO::FETCH_ASSOC));
array_pop($columns);
var_dump($columns);
I make no guarantees that this is valid SQL per ANSI or other, but it works for me.
PDOStatement::getColumnMeta()
As Charle's mentioned, this is a statement method, meaning it fetches the column data from a prepared statement (query).
I needed this and made a simple function to get this done.
function getQueryColumns($q, $pdo){
$stmt = $pdo->prepare($q);
$stmt->execute();
$colCount = $stmt->columnCount();
$return = array();
for($i=0;$i<$colCount;$i++){
$meta = $stmt->getColumnMeta($i);
$return[] = $meta['name'];
}
return $return;
}
Enjoy :)
A very useful solution here for SQLite3. Because the OP does not indicate MySQL specifically and there was a failed attempt to use some solutions on SQLite.
$table_name = 'content_containers';
$container_result = $connect->query("PRAGMA table_info(" . $table_name . ")");
$container_result->setFetchMode(PDO::FETCH_ASSOC);
foreach ($container_result as $conkey => $convalue)
{
$elements[$convalue['name']] = $convalue['name'];
}
This returns an array. Since this is a direct information dump you'll need to iterate over and filter the results to get something like this:
Array
(
[ccid] => ccid
[administration_title] => administration_title
[content_type_id] => content_type_id
[author_id] => author_id
[date_created] => date_created
[language_id] => language_id
[publish_date] => publish_date
[status] => status
[relationship_ccid] => relationship_ccid
[url_alias] => url_alias
)
This is particularly nice to have when the table is empty.
My contribution ONLY for SQLite:
/**
* Returns an array of column names for a given table.
* Arg. $dsn should be replaced by $this->dsn in a class definition.
*
* #param string $dsn Database connection string,
* e.g.'sqlite:/home/user3/db/mydb.sq3'
* #param string $table The name of the table
*
* #return string[] An array of table names
*/
public function getTableColumns($dsn, $table) {
$dbh = new \PDO($dsn);
return $dbh->query('PRAGMA table_info(`'.$table.'`)')->fetchAll(\PDO::FETCH_COLUMN, 1);
}
Just Put your Database name,username,password (Where i marked ?) and table name.& Yuuppiii!.... you get all data from your main database (with column name)
<?php
function qry($q){
global $qry;
try {
$host = "?";
$dbname = "?";
$username = "?";
$password = "?";
$dbcon = new PDO("mysql:host=$host;
dbname=$dbname","$username","$password");
}
catch (Exception $e) {
echo "ERROR ".$e->getMEssage();
}
$qry = $dbcon->query($q);
$qry->setFetchMode(PDO:: FETCH_OBJ);
return $qry;
}
echo "<table>";
/*Get Colums Names in table row */
$columns = array();
$qry1= qry("SHOW COLUMNS FROM Your_table_name");
while (#$column = $qry1->fetch()->Field) {
echo "<td>".$column."</td>";
$columns[] = $column;
}
echo "<tr>";
/* Fetch all data into a html table *
/
$qry2 = qry("SELECT * FROM Your_table_name");
while ( $details = $qry2->fetch()) {
echo "<tr>";
foreach ($columns as $c_name) {
echo "<td>".$details->$c_name."</td>";
}
}
echo "</table>";
?>
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
must be
$q = $dbh->prepare("DESCRIBE database.table");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
There is no need to do a secondary query. Just use the built in oci_field_name() function:
Here is an example:
oci_execute($stid); //This executes
echo "<table border='1'>\n";
$ncols = oci_num_fields($stid);
echo "<tr>";
for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stid, $i);
echo "<td>$column_name</td>";
}
echo "</tr>";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
How can I get all the column names from a table using PDO?
id name age
1 Alan 35
2 Alex 52
3 Amy 15
The info that I want to get are,
id name age
EDIT:
Here is my attempt,
$db = $connection->get_connection();
$select = $db->query('SELECT * FROM contacts');
$total_column = $select->columnCount();
var_dump($total_column);
for ($counter = 0; $counter < $total_column; $counter ++) {
$meta = $select->getColumnMeta($counter);
$column[] = $meta['name'];
}
print_r($column);
Then I get,
Array
(
[0] => id
[1] => name
[2] => age
...
)
I solve the problem the following way (MySQL only)
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
This will work for MySQL, Postgres, and probably any other PDO driver that uses the LIMIT clause.
Notice LIMIT 0 is added for improved performance:
$rs = $db->query('SELECT * FROM my_table LIMIT 0');
for ($i = 0; $i < $rs->columnCount(); $i++) {
$col = $rs->getColumnMeta($i);
$columns[] = $col['name'];
}
print_r($columns);
My 2 cents:
$result = $db->query('select * from table limit 1');
$fields = array_keys($result->fetch(PDO::FETCH_ASSOC));
And you will get the column names as an array in the var $fields.
$sql = "select column_name from
information_schema.columns where
table_name = 'myTable'";
PHP function
credits : http://www.sitepoint.com/forums/php-application-design-147/get-pdo-column-name-easy-way-559336.html
function getColumnNames()
{
$sql = "SELECT column_name FROM information_schema.columns WHERE table_name = 'myTable'";
#$sql = 'SHOW COLUMNS FROM ' . $this->table;
$stmt = $this->connection->prepare($sql);
try {
if ($stmt->execute())
{
$raw_column_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($raw_column_data as $outer_key => $array)
{
foreach($array as $inner_key => $value
{
if (!(int)$inner_key)
{
$this->column_names[] = $value;
}
}
}
}
return $this->column_names;
}
catch (Exception $e)
{
return $e->getMessage(); //return exception
}
}
Here is the function I use. Created based on #Lauer answer above and some other resources:
//Get Columns
function getColumns($tablenames) {
global $hostname , $dbnames, $username, $password;
try {
$condb = new PDO("mysql:host=$hostname;dbname=$dbnames", $username, $password);
//debug connection
$condb->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$condb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// get column names
$query = $condb->prepare("DESCRIBE $tablenames");
$query->execute();
$table_names = $query->fetchAll(PDO::FETCH_COLUMN);
return $table_names;
//Close connection
$condb = null;
} catch(PDOExcepetion $e) {
echo $e->getMessage();
}
}
Usage Example:
$columns = getColumns('name_of_table'); // OR getColumns($name_of_table); if you are using variable.
foreach($columns as $col) {
echo $col . '<br/>';
}
This is an old question but here's my input
function getColumns($dbhandle, $tableName) {
$columnsquery = $dbhandle->query("PRAGMA table_info($tableName)");
$columns = array();
foreach ($columnsquery as $k) {
$columns[] = $k['name'];
}
return $columns;
}
just put your variable for your pdo object and the tablename. Works for me
This approach works for me in SQLite and MySQL. It may work with others, please let me know your experience.
Works if rows are present
Works if no rows are present (test with DELETE FROM table)
Code:
$calendarDatabase = new \PDO('sqlite:calendar-of-tasks.db');
$statement = $calendarDatabase->query('SELECT *, COUNT(*) FROM data LIMIT 1');
$columns = array_keys($statement->fetch(PDO::FETCH_ASSOC));
array_pop($columns);
var_dump($columns);
I make no guarantees that this is valid SQL per ANSI or other, but it works for me.
PDOStatement::getColumnMeta()
As Charle's mentioned, this is a statement method, meaning it fetches the column data from a prepared statement (query).
I needed this and made a simple function to get this done.
function getQueryColumns($q, $pdo){
$stmt = $pdo->prepare($q);
$stmt->execute();
$colCount = $stmt->columnCount();
$return = array();
for($i=0;$i<$colCount;$i++){
$meta = $stmt->getColumnMeta($i);
$return[] = $meta['name'];
}
return $return;
}
Enjoy :)
A very useful solution here for SQLite3. Because the OP does not indicate MySQL specifically and there was a failed attempt to use some solutions on SQLite.
$table_name = 'content_containers';
$container_result = $connect->query("PRAGMA table_info(" . $table_name . ")");
$container_result->setFetchMode(PDO::FETCH_ASSOC);
foreach ($container_result as $conkey => $convalue)
{
$elements[$convalue['name']] = $convalue['name'];
}
This returns an array. Since this is a direct information dump you'll need to iterate over and filter the results to get something like this:
Array
(
[ccid] => ccid
[administration_title] => administration_title
[content_type_id] => content_type_id
[author_id] => author_id
[date_created] => date_created
[language_id] => language_id
[publish_date] => publish_date
[status] => status
[relationship_ccid] => relationship_ccid
[url_alias] => url_alias
)
This is particularly nice to have when the table is empty.
My contribution ONLY for SQLite:
/**
* Returns an array of column names for a given table.
* Arg. $dsn should be replaced by $this->dsn in a class definition.
*
* #param string $dsn Database connection string,
* e.g.'sqlite:/home/user3/db/mydb.sq3'
* #param string $table The name of the table
*
* #return string[] An array of table names
*/
public function getTableColumns($dsn, $table) {
$dbh = new \PDO($dsn);
return $dbh->query('PRAGMA table_info(`'.$table.'`)')->fetchAll(\PDO::FETCH_COLUMN, 1);
}
Just Put your Database name,username,password (Where i marked ?) and table name.& Yuuppiii!.... you get all data from your main database (with column name)
<?php
function qry($q){
global $qry;
try {
$host = "?";
$dbname = "?";
$username = "?";
$password = "?";
$dbcon = new PDO("mysql:host=$host;
dbname=$dbname","$username","$password");
}
catch (Exception $e) {
echo "ERROR ".$e->getMEssage();
}
$qry = $dbcon->query($q);
$qry->setFetchMode(PDO:: FETCH_OBJ);
return $qry;
}
echo "<table>";
/*Get Colums Names in table row */
$columns = array();
$qry1= qry("SHOW COLUMNS FROM Your_table_name");
while (#$column = $qry1->fetch()->Field) {
echo "<td>".$column."</td>";
$columns[] = $column;
}
echo "<tr>";
/* Fetch all data into a html table *
/
$qry2 = qry("SELECT * FROM Your_table_name");
while ( $details = $qry2->fetch()) {
echo "<tr>";
foreach ($columns as $c_name) {
echo "<td>".$details->$c_name."</td>";
}
}
echo "</table>";
?>
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
must be
$q = $dbh->prepare("DESCRIBE database.table");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
There is no need to do a secondary query. Just use the built in oci_field_name() function:
Here is an example:
oci_execute($stid); //This executes
echo "<table border='1'>\n";
$ncols = oci_num_fields($stid);
echo "<tr>";
for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stid, $i);
echo "<td>$column_name</td>";
}
echo "</tr>";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
I am trying to write prepared statement for IN clause where array is mixed array. i am able to build array for 'call_user_func_array()' but i am not able to prepare statement. no output is showing.
this is my php code:
$search1 = array('pune','india','2014','mumbai','2015');
print_r($search1);
echo $param = implode(",",$search1);
$ids = array_flip(array_flip(explode(',', $param)));
var_dump($ids);
$type1 = array();
foreach ($ids as $element) {
if(is_string($element)) {
$type1[] ='s';
}elseif(is_int($element)) {
$type1[] ='i';
}
}
print_r($type1);
echo $type=implode("",$type1);
$inputArray[] = &$type;
$j = count($ids);
for($i=0;$i<$j;$i++){
$inputArray[] = &$ids[$i];
}
print_r($inputArray);
echo $clause = implode(',', array_fill(0, count($ids), '?'));
$construct .="(city in ('.$clause.') or state in ('.$clause.')
or country in ('.$clause.')) AND year in ('.$clause.') order by year desc";
$constructs ="SELECT * FROM info WHERE $construct";
if($stmt1 = mysqli_prepare($conn, $constructs)){
call_user_func_array(array($stmt1,'bind_param'),$inputArray);
if(mysqli_stmt_execute($stmt1)){
$result = mysqli_stmt_get_result($stmt1);
if(mysqli_num_rows($result) > 0){
echo $foundnum = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo $id = $row['id'];
echo $name = $row['name'];
}
}
}
}
mysqli_stmt_close($stmt1);
please tell me what i am doing wrong here.
100% Tested and Successful Code:
$search1 = ['2014','pune','india','2014','mumbai','2015','mumbai'];
// Separate logically and remove duplicates
foreach ($search1 as $value) {
if (strlen($value)==4 && ctype_digit($value)) { // qualifies for the year column
$years[$value] = null;
} else {
$strings[$value] = null;
}
}
$years = array_keys($years); // move keys to values
$years_count = sizeof($years);
$strings = array_keys($strings); // move keys to values
$strings_count = sizeof($strings);
if (!$years_count || !$strings_count) { // this is a matter of program logic
echo "A minimum of one year value and one non-year value is required for search functionality.";
}elseif (!$conn = new mysqli("host", "user","pass","db")) {
echo "Database Connection Error: " , $conn->connect_error; // don't show to the public
} else {
$years_csph = implode(',', array_fill(0, $years_count, '?')); // comma-separated placeholders
$strings_csph = implode(',', array_fill(0, $strings_count, '?')); // comma-separated placeholders
$total_count = $strings_count * 3 + $years_count;
$total_params = array_merge($strings, $strings, $strings, $years);
$param_string = str_repeat('s', $strings_count * 3) . str_repeat('i', $years_count); // write s chars before i chars
if(!$stmt = $conn->prepare("SELECT id, name FROM info WHERE (city IN ($strings_csph) OR state IN ($strings_csph) OR country IN ($strings_csph)) AND year IN ($years_csph) ORDER BY year DESC")) {
echo "Syntax Error # prepare: " , $conn->error; // don't show to public
}else{
array_unshift($total_params, $param_string); // prepend the type values string
$ref = []; // add references
foreach ($total_params as $i => $v) {
$ref[$i] = &$total_params[$i]; // pass by reference as required/advised by the manual
}
call_user_func_array([$stmt, 'bind_param'], $ref);
if (!$stmt->execute()) {
echo "Error # bind_param/execute: " , $stmt->error; // don't show to public
} elseif (!$stmt->bind_result($id, $name)) {
echo "Error # bind_result: " , $stmt->error; // don't show to public
} else {
while ($stmt->fetch()) {
echo "<div>$id : $name</div>";
}
$stmt->close();
}
}
}
Among other potential problems, '.$clause.' didn't look good because it was writing single quotes and dots around your placeholders. Placeholder never need single quoting and that syntax would have been incorrect even if they did.
I am trying to do following
$statement = $conn->prepare('SELECT * FROM myTable');
$statement->execute();
if(!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
{
return false;
}
$conn = null;
} catch(PDOException $e) {
throw $e;
return false;
}
return return json_encode(array('Result'=>$row);
Works and fetches all entries in a table make then JSON Array and send them,
However I want to make a query where selected ids must be send in a JSON Array
E.g 10, 20, 30
I assume that this will be done in a For loop perhaps
$statement = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
$row = $statement->fetch(PDO::FETCH_OBJ)))
Now suppose i have id's = 10,20,30 i want to append all of them in a JSON Array How can i do that?
just like return json_encode(array('Result'=>$row);
Edited Code
function GetMyMembers()
{
$myId = trim($_REQUEST['myId']);
try {
$conn = $this->GetDBConnection();
$statement = $conn->prepare('SELECT valId FROM memList WHERE myId=:myId' );
$statement->bindParam(':myId', $myId, PDO::PARAM_INT);
$statement->execute();
if(!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
{
return false;
}
// $row contains ALL THE ID'S
$placeholders = str_repeat('?,', count($row));
$placeholders = substr($placeholders, 0, -1);
$sql = "SELECT id, * FROM players WHERE id IN ($placeholders)";
$statement = $conn->prepare($sql);
$statement->execute($row);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
$conn = null;
} catch(PDOException $e) {
throw $e;
return false;
}
return $rows;
}
$statement = $conn->prepare('SELECT * FROM myTable');
$statement->execute();
$data = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC)))
{
$data[$row['id']] = $row;
}
return json_encode(array('Result'=>$data));
Btw, using raw API is not convenient. With Database abstraction library your code can be as short as 2 following lines:
$data = $db->getInd("id",'SELECT * FROM myTable');
return json_encode(array('Result'=>$data));
Edit:
if you have an array of ids, you need more complex code
$ids = array(1,2,3);
$data = array();
$statement = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
foreach ($ids as $id) {
$statement->bindValue(':id', $id, PDO::PARAM_STR);
$statement->execute();
$data[] = $statement->fetch(PDO::FETCH_OBJ);
}
return json_encode(array('Result'=>$data));
But while using Database abstraction library, there will be the same 2 lines:
$data = $db->getAll('SELECT * FROM myTable where id IN (?a)', $ids);
return json_encode(array('Result'=>$data));
Edit2:
if you need ids only
$statement = $conn->prepare('SELECT id FROM myTable');
$statement->execute();
$data = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC)))
{
$data[] = $row['id'];
}
return json_encode(array('Result'=>$data));
while using Database abstraction library, it's still 2 lines:
$ids = $db->getCol('SELECT id FROM myTable');
return json_encode(array('Result'=>$ids));
$ids = array(1,2,3);
$placeholders = str_repeat('?,', count($ids));
$placeholders = substr($placeholders, 0, -1);
$sql = "SELECT id, * FROM table WHERE id IN ($placeholders)";
$sth = $dbh->prepare($sql);
$sth->execute($ids);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
echo json_encode(array('Result' => $rows));
Based on additional comments:
Best option:
$sql = '
SELECT *
FROM table1 AS t1
INNER JOIN table2 t2
ON t2.foreign_key = t1.id
';
or
$sql = 'SELECT id FROM table1';
$sth = $dbh->prepare($sth);
$sth->execute();
$ids = $sth->fetchColumn();
//next look above
How can I get all the column names from a table using PDO?
id name age
1 Alan 35
2 Alex 52
3 Amy 15
The info that I want to get are,
id name age
EDIT:
Here is my attempt,
$db = $connection->get_connection();
$select = $db->query('SELECT * FROM contacts');
$total_column = $select->columnCount();
var_dump($total_column);
for ($counter = 0; $counter < $total_column; $counter ++) {
$meta = $select->getColumnMeta($counter);
$column[] = $meta['name'];
}
print_r($column);
Then I get,
Array
(
[0] => id
[1] => name
[2] => age
...
)
I solve the problem the following way (MySQL only)
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
This will work for MySQL, Postgres, and probably any other PDO driver that uses the LIMIT clause.
Notice LIMIT 0 is added for improved performance:
$rs = $db->query('SELECT * FROM my_table LIMIT 0');
for ($i = 0; $i < $rs->columnCount(); $i++) {
$col = $rs->getColumnMeta($i);
$columns[] = $col['name'];
}
print_r($columns);
My 2 cents:
$result = $db->query('select * from table limit 1');
$fields = array_keys($result->fetch(PDO::FETCH_ASSOC));
And you will get the column names as an array in the var $fields.
$sql = "select column_name from
information_schema.columns where
table_name = 'myTable'";
PHP function
credits : http://www.sitepoint.com/forums/php-application-design-147/get-pdo-column-name-easy-way-559336.html
function getColumnNames()
{
$sql = "SELECT column_name FROM information_schema.columns WHERE table_name = 'myTable'";
#$sql = 'SHOW COLUMNS FROM ' . $this->table;
$stmt = $this->connection->prepare($sql);
try {
if ($stmt->execute())
{
$raw_column_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($raw_column_data as $outer_key => $array)
{
foreach($array as $inner_key => $value
{
if (!(int)$inner_key)
{
$this->column_names[] = $value;
}
}
}
}
return $this->column_names;
}
catch (Exception $e)
{
return $e->getMessage(); //return exception
}
}
Here is the function I use. Created based on #Lauer answer above and some other resources:
//Get Columns
function getColumns($tablenames) {
global $hostname , $dbnames, $username, $password;
try {
$condb = new PDO("mysql:host=$hostname;dbname=$dbnames", $username, $password);
//debug connection
$condb->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$condb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// get column names
$query = $condb->prepare("DESCRIBE $tablenames");
$query->execute();
$table_names = $query->fetchAll(PDO::FETCH_COLUMN);
return $table_names;
//Close connection
$condb = null;
} catch(PDOExcepetion $e) {
echo $e->getMessage();
}
}
Usage Example:
$columns = getColumns('name_of_table'); // OR getColumns($name_of_table); if you are using variable.
foreach($columns as $col) {
echo $col . '<br/>';
}
This is an old question but here's my input
function getColumns($dbhandle, $tableName) {
$columnsquery = $dbhandle->query("PRAGMA table_info($tableName)");
$columns = array();
foreach ($columnsquery as $k) {
$columns[] = $k['name'];
}
return $columns;
}
just put your variable for your pdo object and the tablename. Works for me
This approach works for me in SQLite and MySQL. It may work with others, please let me know your experience.
Works if rows are present
Works if no rows are present (test with DELETE FROM table)
Code:
$calendarDatabase = new \PDO('sqlite:calendar-of-tasks.db');
$statement = $calendarDatabase->query('SELECT *, COUNT(*) FROM data LIMIT 1');
$columns = array_keys($statement->fetch(PDO::FETCH_ASSOC));
array_pop($columns);
var_dump($columns);
I make no guarantees that this is valid SQL per ANSI or other, but it works for me.
PDOStatement::getColumnMeta()
As Charle's mentioned, this is a statement method, meaning it fetches the column data from a prepared statement (query).
I needed this and made a simple function to get this done.
function getQueryColumns($q, $pdo){
$stmt = $pdo->prepare($q);
$stmt->execute();
$colCount = $stmt->columnCount();
$return = array();
for($i=0;$i<$colCount;$i++){
$meta = $stmt->getColumnMeta($i);
$return[] = $meta['name'];
}
return $return;
}
Enjoy :)
A very useful solution here for SQLite3. Because the OP does not indicate MySQL specifically and there was a failed attempt to use some solutions on SQLite.
$table_name = 'content_containers';
$container_result = $connect->query("PRAGMA table_info(" . $table_name . ")");
$container_result->setFetchMode(PDO::FETCH_ASSOC);
foreach ($container_result as $conkey => $convalue)
{
$elements[$convalue['name']] = $convalue['name'];
}
This returns an array. Since this is a direct information dump you'll need to iterate over and filter the results to get something like this:
Array
(
[ccid] => ccid
[administration_title] => administration_title
[content_type_id] => content_type_id
[author_id] => author_id
[date_created] => date_created
[language_id] => language_id
[publish_date] => publish_date
[status] => status
[relationship_ccid] => relationship_ccid
[url_alias] => url_alias
)
This is particularly nice to have when the table is empty.
My contribution ONLY for SQLite:
/**
* Returns an array of column names for a given table.
* Arg. $dsn should be replaced by $this->dsn in a class definition.
*
* #param string $dsn Database connection string,
* e.g.'sqlite:/home/user3/db/mydb.sq3'
* #param string $table The name of the table
*
* #return string[] An array of table names
*/
public function getTableColumns($dsn, $table) {
$dbh = new \PDO($dsn);
return $dbh->query('PRAGMA table_info(`'.$table.'`)')->fetchAll(\PDO::FETCH_COLUMN, 1);
}
Just Put your Database name,username,password (Where i marked ?) and table name.& Yuuppiii!.... you get all data from your main database (with column name)
<?php
function qry($q){
global $qry;
try {
$host = "?";
$dbname = "?";
$username = "?";
$password = "?";
$dbcon = new PDO("mysql:host=$host;
dbname=$dbname","$username","$password");
}
catch (Exception $e) {
echo "ERROR ".$e->getMEssage();
}
$qry = $dbcon->query($q);
$qry->setFetchMode(PDO:: FETCH_OBJ);
return $qry;
}
echo "<table>";
/*Get Colums Names in table row */
$columns = array();
$qry1= qry("SHOW COLUMNS FROM Your_table_name");
while (#$column = $qry1->fetch()->Field) {
echo "<td>".$column."</td>";
$columns[] = $column;
}
echo "<tr>";
/* Fetch all data into a html table *
/
$qry2 = qry("SELECT * FROM Your_table_name");
while ( $details = $qry2->fetch()) {
echo "<tr>";
foreach ($columns as $c_name) {
echo "<td>".$details->$c_name."</td>";
}
}
echo "</table>";
?>
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
must be
$q = $dbh->prepare("DESCRIBE database.table");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
There is no need to do a secondary query. Just use the built in oci_field_name() function:
Here is an example:
oci_execute($stid); //This executes
echo "<table border='1'>\n";
$ncols = oci_num_fields($stid);
echo "<tr>";
for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stid, $i);
echo "<td>$column_name</td>";
}
echo "</tr>";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";