Reputation: 179
I have been researching for days now. I always get something like this (this is what I think is the best answer):
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
AND `TABLE_NAME`='yourtablename';
Yeah this one runs perfectly in SQL, but I still have no idea how I will create a PHP script to show it the same way as it does in SQL. Can anyone give me a code?
I'm really confused right now. Please help..
Upvotes: 1
Views: 171
Reputation: 57342
you can do this by in mysql mysql_field_name()
Use of mysql_*
is discouraged so use either pdo
or mysqli
with them you can do this by
mysqli_fetch_field_direct() //for mysqli
PDOStatement::getColumnMeta() //for pdo
for example after OP comment
$sql = "SELECT * from Person";
$result = mysql_query($sql,$con);
$name = mysql_field_name($result, 0);
explanation how to use the mysql_field_name()
Syntex
mysql_field_name(data,fieldOffset)
+------------+------------------------------------------------------------------+
| data | Required. Specifies which data pointer to use. The data |
| | pointer is the result from the mysql_query() function |
+------------+------------------------------------------------------------------+
|fieldOffset |Required. Specifies which field to start returning. 0 indicates |
| |the first field |
+------------+------------------------------------------------------------------+
good read
PDO Tutorial for MySQL Developers
Upvotes: 1
Reputation: 6854
without PDO:
$sql = "SHOW FIELDS FROM users;";
$result_sql = mysql_query($sql) or die ("Error!\n");
while ($row = mysql_fetch_array($result_sql)) {
echo $row['Field']."<br>\n";
}
Upvotes: 2
Reputation: 14295
Apparently you need to retrieve data from a mysql table and then do stuff with it in php. There are several ways to do this, here is my favorite:
<?php
$query="SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
AND `TABLE_NAME`='yourtablename'";
$result=mysql_query($query); //This will store the whole result table in $result
$rows=array(); //Initialize array
while($row=mysql_fetch_object($result)) $rows[]=(object) $row; //Store each row of the result table in the array $rows
//Now you can access, for example, the third row and second column by saying:
echo $rows[2]->name_of_second_column
?>
Also refer to this tutorial. on how to retrieve data from a database and manipulate it afterwards.
Upvotes: 1