I am looking to populate an array of all columns that are being viewed in a query lets say
$sql='SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
FROM tutorials_tbl a, tcount_tbl b
WHERE a.tutorial_author = b.tutorial_author';
function getColoumns($sql) {
$result = mysql_query("SHOW COLUMNS FROM (". $sql."));
if (!$result) {
echo 'Could not run query: ' . mysql_error();
}
$fieldnames=array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$fieldnames[] = $row['Field'];
}
}
return $fieldnames;
}
I cant seem to get it right. Anyone out there who can help me out. Thanks in Advance.
SHOW COLUMNS
does not allow for a subselect statement according to the MySQL documentation.
You could instead go for a combination of the original query, mysql_num_fields()
and mysql_field_name()
:
function getColoumns($sql) {
$result = mysql_query( $sql );
if (!$result) {
echo 'Could not run query: ' . mysql_error();
// return from function here. don't know what value you need.
return array()
}
$fieldnames = array();
$fieldCount = mysql_num_fields($result);
for( $i=0; $i<$fieldCount; $i++ ) {
$fieldnames[] = mysql_field_name( $result , $i );
}
return $fieldnames;
}
Besides, take a look at Why shouldn't I use mysql_* functions in PHP? and/or make sure the query is not malicious!