Skip to content

Instantly share code, notes, and snippets.

@Exadra37
Last active January 4, 2016 09:49
Show Gist options
  • Select an option

  • Save Exadra37/8605067 to your computer and use it in GitHub Desktop.

Select an option

Save Exadra37/8605067 to your computer and use it in GitHub Desktop.
This is a function easily convertible into a method to use inside of a class that as the name says, get columns names from mysql table, will return all the columns names from a given table in the provided database. The mysql connection used is the native PHP driver PDO. The difference to other one that i also have here in Gist is that this one u…
<?php
/**
* getAllColumnsNamesFromMysqlTable.php
*
* @author Paulo Silva(Exadra37) exadra37 in gmail point com
* @package exadra37/PDO
* @version 0.0.2
* @since 24/01/2014 - v.0.0.1
* 25/01/2014 - v.0.0.2
*
*/
// Report all PHP Errors
error_reporting(E_ALL);
// Set execution time to unlimited
set_time_limit(0);
// Use UK Time
date_default_timezone_set('Europe/London');
// THIS IS THE CONTENT OF SETTINGS.INC.PHP:
// define('_DB_NAME_', 'your_database_name');
// define('_DB_TABLE_NAME_', 'your_table_name');
// define('_DB_USER_NAME_', 'your_user_name');
// define('_DB_PASSWORD_', 'your_password');
// define('_DB_HOST_', 'localhost');
require_once 'config/settings.inc.php';
/**
* Database Settings from defined constants in config/settings.inc.php
*
* IMPORTANT: - Never put this information in your script
* - Always retrieve it from a config file
* - The folder where the config file resides should be protected with a .htaccess file containing the line "deny from all"
*/
$host = _DB_HOST_;
$database_name = _DB_NAME_;
$table_name = _DB_TABLE_NAME_;
/**
* getAllColumnsNamesFromMysqlTable
* - As the name says will return all the columns names from the mysql table.
*
* @param string $host - can be: localhost, 127.0.0.1, ip address or domain name
* @param string $database_name - The name of your database
* @param string $table_name - The name of the table in database
* @return array - On success:
* array(
* 'pdo_rows_count' => integer,
* 'mysql_columns_names' => array()
* )
* - On error:
* array(
* 'pdo_exception' => integer,
* )
*
*/
function getAllColumnsNamesFromMysqlTable($host, $database_name, $table_name)
{
try {
// Creating a connection to mysl database
// If you already have a PDO connection instantiated uncomment the line 71 and do the following:
// - rename the function to getAllColumnsNamesFromMysqlTable($PDO)
// - Then call the function like this: getAllColumnsNamesFromMysqlTable($your_pdo_connection)
$PDO = new PDO("mysql:host={$host};dbname={$database_name}", _DB_USER_NAME_, _DB_PASSWORD_);
// Setting error level
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Building the query
$query = "
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`= :database_name
AND `TABLE_NAME`= :table_name";
// Binding the values(database_name, table_name) to the query
// This method is good to prevent sql injection
// http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/
// http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
$bind = array(
'database_name' => $database_name,
'table_name' => $table_name
);
// Prepare the query for execution
// At this moment the query don't have yet the values
$select = $PDO->prepare($query);
// Binding the values to the placeholders (:database_name, :table_name) presents in the query
$select->execute($bind);
// Get the number of rows that mysql have returned
$result['pdo_rows_count'] = $select->rowCount();
// Loop the results to retrieve only what we need in a better format
// var_dump($result['mysql_columns_names']) will return:
// array (size=4)
// 0 => string 'recid' (length=5)
// 1 => string 'rcode' (length=5)
// 2 => string 'storeName' (length=9)
// 3 => string 'scode' (length=5)
while ($row = $select->fetch()) {
$result['mysql_columns_names'][] = $row['COLUMN_NAME'];
}
} catch (PDOException $e) {
// Retrieves the error for posterior handling
$result['pdo_exception'] = 'ERROR: '.$e->getMessage();
}
return $result ;
}
// How to call the function
$result = getAllColumnsNamesFromMysqlTable($host, $database_name, $table_name);
/**
* HOW TO WORK WITH THE RESULT
*/
// Checking for errors
if (isset($result['pdo_exception'])) {
// Do something with the error
die($result['pdo_exception']);
}
// Assigning the number o rows returned from PDO
$pdo_rows_count = $result['pdo_rows_count'];
// Assigning all the columns names from the mysql table
$mysql_columns_names = $result['mysql_columns_names'];
/**
* Now use the data according with your needs
*/
// Uncomment following 3 lines to debug results
echo '<pre><hr>';
print_r($result);
echo '</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment