I have a function which selects the * values from a particular table, I need to configure that if I pass * in parameter then it selects all or the selected parameters.
My function is as follows:
public function select($tablename){
$select = mysql_query("SELECT * FROM $tablename");
if(!$select){
echo "cant select table mane";
}
while ($row = mysql_fetch_array($select)){
print_r($row);
}
}
How can I pass the dynamic colum name in place of *
public function select($tablename,$column=NULL){
if($column == null) {
$select = mysql_query("SELECT * FROM $tablename");
} else {
$select = mysql_query("SELECT ".$column." FROM $tablename");
}
call it using select("abcd_table","id,name"); OR for all just select("abcd_table");
By Alex
Avoid mysql, it is deprecated. Use mysqli or PDO instead
That's even easier:
public function select( $tablename , $columnName = array() ){
$columnName = $columnName ? implode( ',' , $columnName ) : '*';
$select = mysql_query( 'SELECT ' . $columnName . ' FROM ' . $tableName );
if(!$select){
echo "cant select table mane";
}
while ($row = mysql_fetch_array($select)){
print_r($row);
}
}
Add one more parameter $columnname type array in your function.
public function select($tablename,$columnname = array()){
if(count($columnname)){
$columnname = implode(",",$columnname);
$select = mysql_query("SELECT {$columnname} FROM $tablename");
}
else{
$select = mysql_query("SELECT * FROM $tablename");
}
#code continue
}
Calling will be like below
To select all fields,
select($tablename);
To select some fields,
select($tablename,array('field','field2'));
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
public function select($tablename, $selectrow){
$select = mysql_query("SELECT $selectrow FROM $tablename");
if(!$select){
echo "cant select table mane";
}
while ($row = mysql_fetch_array($select)){
print_r($row);
}
}
try this modified function
public function select($tablename,$array_fields){
if(!empty($array_fields)){
$fieldstr = implode(',',$array_fields);
$fieldstr = trim($fieldstr,',');
}else{
$fieldstr = '*';
}
$select = mysql_query("SELECT $fieldstr FROM $tablename");
if(!$select){
echo "cant select table mane";
}
while ($row = mysql_fetch_array($select)){
print_r($row);
}
}
public function select($tablename,$column="*"){
$select = mysql_query("SELECT $column FROM $tablename");
if(!$select){
echo "cant select table mane";
}
while ($row = mysql_fetch_array($select)){
print_r($row);
}
}
call like select("table","*") or
call like select("table","col1,col2")
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";
Here is my code:
case 'records': $this-> get_records ($callParams[1]);
private function get_records($id)
{
$result = get_records_info ($id) ;
if(count($result) > 0)
$this->response($this->text/html($result), 200);
else
$this->response('',204);
}
function get_records_info (){
$result = mysql_query ("SELECT * FROM `records` ")
or die(mysql_error());
while($records = mysql_fetch_array( $result )) {
echo "<div>" .$records['records_name']. "</div>";
echo "<div>info:" .$records['w']. $records['l']. $records['d']. $records['k']."</div>";
echo "<div>info2:".$records['info2']."</div>";
}
}
Here is what I'm trying to do:
When you click on records is goes to domain.com/record/id and only displays the record of that id.
Here is what is happening:
I got it to work but I'm getting all the records in the database.
Your result is currently:
mysql_query ("SELECT * FROM `records` ")
This is going to grab all the records regardless. What you want is something like this:
mysql_query ("SELECT * FROM `records` WHERE `id` = '$id' ")
$id being the supplied id to fetch the record for.
Note: As stated in the comments, stay away from mysql_* functions as it is depreciated. Look into PDO or MySQLi :)
try this.... You are passing the id in function but not using thats why it is showing you all recrods, pass id in function function get_records_info ($id) then in query .
<?php
//case 'records': $this-> get_records ($callParams[1]);
case 'records': $this-> get_records ($id); //just pass the id of the user here
private function get_records($id)
{
$result = get_records_info ($id) ;
if(count($result) > 0)
$this->response($this->text/html($result), 200);
else
$this->response('',204);
}
function get_records_info ($id){
$result = mysql_query ("SELECT * FROM `records` where `id` = ' ".$id." ' ")
or die(mysql_error());
while($records = mysql_fetch_array( $result )) {
echo "<div>" .$records['records_name']. "</div>";
echo "<div>info:" .$records['w']. $records['l']. $records['d']. $records['k']."</div>";
echo "<div>info2:".$records['info2']."</div>";
}
}
?>
I have a way to get the name of the columns of a table. It works fine but now I want to update to the new mysqli ? (I tried the mysqli_fetch_field but I don't know how to apply to this case and I am not sure if it is the wright option)
How to do the same with mysqli ? :
$sql = "SELECT * from myTable";
$result = mysql_query($sql,$con);
$id = mysql_field_name($result, 0);
$a = mysql_field_name($result, 1);
echo $id;
echo $a;
This is the way to implement this missing function:
function mysqli_field_name($result, $field_offset)
{
$properties = mysqli_fetch_field_direct($result, $field_offset);
return is_object($properties) ? $properties->name : null;
}
I'm not sure if there is a better way to do that, but I checked that this works to get just the name of the columns and is the new mysqli :
$result = mysqli_query($con, 'SELECT * FROM myTable');
while ($property = mysqli_fetch_field($result)) {
echo $property->name;
}
You can replace the function mysql_field_name to mysqli_fetch_field_directand use it like the following:
$colObj = mysqli_fetch_field_direct($result,$i);
$col = $colObj->name;
echo "<br/>Coluna: ".$col;
This is another easy way to print each field's name, table, and max length
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
printf("Name: %s\n",$fieldinfo->name);
printf("Table: %s\n",$fieldinfo->table);
printf("max. Len: %d\n",$fieldinfo->max_length);
}
// Free result set
mysqli_free_result($result);
}
$sql = "SELECT * FROM myTable LIMIT 10";
$ressult = $con->query($sql);
$rows = $result->fetch_all(MYSQLI_ASSOC);
$fields = array_keys($rows[0] ?? []);
echo json_encode($fields);
Can return empty array if query returned no rows.
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";