View Full Version : Get column names with SHOW COLUMNS
binaryWeapon
08-04-2008, 06:05 PM
How would I retrieve just the column names using SHOW COLUMNS or DESCRIBE in PHP? It doesn't matter if its as mysql_result_assoc or mysql_result_array or anything else, just so long as I can retrieve the values. Using mysql_result_array it only seems to retrieve information about the first column.
I have this: $result = mysql_query("SHOW COLUMNS FROM ".$contentGroup);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
}
$fieldnames=array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
// What to put here?
}
}
I just need to know how to navigate that array to retrieve the field names. I thought it would be $row["field"] or $row[0] but neither worked.
Fou-Lu
08-04-2008, 09:41 PM
I'm not sure what the trouble is that code is correct. If you do a print_r($row) within you're loop it should list each of the table fields.
The code you're looking for should just be $fieldnames[] = $row['Field'];. That may be the trouble you're having now that I see it, I'm pretty sure that show columns returns keys that are title cased, so you need to use uppercase Field instead of field. Try that out, see if that one works for you.
oesxyl
08-04-2008, 10:05 PM
How would I retrieve just the column names using SHOW COLUMNS or DESCRIBE in PHP? It doesn't matter if its as mysql_result_assoc or mysql_result_array or anything else, just so long as I can retrieve the values. Using mysql_result_array it only seems to retrieve information about the first column.
I have this: $result = mysql_query("SHOW COLUMNS FROM ".$contentGroup);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
}
$fieldnames=array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
// What to put here?
}
}
I just need to know how to navigate that array to retrieve the field names. I thought it would be $row["field"] or $row[0] but neither worked.
this kind of problem are easy to solve using print_r or var_dump. A print_r($row) will show you the keys and the value of each item so further you can use the key to retrive value.
column name in mysql is not case sensitive but I guess in php is, so must work with $row['Field'] as Fou-Lu said.regards
binaryWeapon
08-05-2008, 12:15 AM
Alright thanks, using $row["Field"] works, I didn't realize it was case-sensitive.
Thanks! :)
vBulletin® v3.8.2, Copyright ©2000-2009, Jelsoft Enterprises Ltd.