Excerpt |
---|
PDO provides a method to get database field name (column name) from the query result. |
Below code shows the example:
Code Block |
---|
|
$p = new PDO( "mysql:host=localhost;dbname=foo;charset=utf8", "chun", "kang");
$select = $p->query("select * from test_table");
$fieldname = $select->fetch(PDO::FETCH_ASSOC); |
Below code is another example to get query result and field name in PHP:
Code Block |
---|
|
$m_db = new stdClass();
$m_db->connection = NULL;
$m_db->user = "user name";
$m_db->userpasswd = "user password";
$m_db->database = "database name";
function mydb_open()
{
global $m_db;
if ($m_db->connection==NULL) try {
$dsn = 'mysql:host=localhost;dbname=' . $m_db->database . ';charset=utf8';
$m_db->connection = new PDO($dsn, $m_db->user, $m_db->userpasswd);
}
catch (PDOException $exc) {
$m_db->connection = NULL;
echo "DB open failure!!";
exit;
}
return $m_db->connection;
}
function mydb_close()
{
global $m_db;
$m_db->connection=NULL;
}
function mydb_execl( $sql, $debug=0)
{
global $m_db;
$ret=0;
if (mydb_open()) {
$pResult=$m_db->connection->exec( $sql);
if ($pResult) {
$ret=1;
}
}
else {
$ret=0;
}
mydb_close();
return $ret;
}
function mydb_query_full($sql, &$columnName, $debug=0)
{
global $m_db;
if (mydb_open()) {
if ($debug) echo "db open - ok<br>\n";
$select = $m_db->connection->query($sql);
$ret=null;
if ($select) {
if ($debug) echo "db query - ok<br>\n";
// get query result
while( $row = $select->fetch()) $ret[] = $row;
// check column information
$sql = preg_replace( "/ limit(.*)/", "", $sql) . " limit 1";
$select = $m_db->connection->query($sql);
if ($debug) echo "Checking column name<br>\n";
$columnName = array_keys($select->fetch(PDO::FETCH_ASSOC));
if ($debug) {
echo "<pre>";
var_dump($columnName);
echo "</pre>";
}
}
mydb_close();
if ($debug) {
echo "Query result:<br>\n";
echo "<pre>";
var_dump($ret);
echo "</pre>";
}
if ($debug && is_array($ret)) echo "result count = " . count($ret) . "<br>\n";
return $ret;
}
else {
return null;
}
} |