RESOLVED I have used the answer from alfasin, but as that gave me WAY too much information, i wrote a little script to just get the field names. As the field names apeared first, it was rather simple:
$here = array();
$SQL = "SHOW COLUMNS FROM User";
foreach($conn->query($SQL) as $row) {
$here[] = $row[0];
}
echo '<pre>';print_r($here);echo '<pre>';
This left me with the new array $here
containing the column names, hope this helps someone in the future :)
Original question:
Let me clarify a bit, I have a mysql table and I'm trying to select * from it, and display the result in an html list <ol>
. I can manage to grab the row data JUST FINE, but I cannot for the life of me figure out how to grab the table column names, in order to match them up with the row, respectively. this is my code that is grabbing the row data:
//get those results
$sql = "SELECT DISTINCT *
FROM User
WHERE Owner = '".$owner."'";
foreach($conn->query($sql) as $row) {
//split array in half
$hax = count($row);
$halfHax = $hax / 2;
//set up a for loop to give results
$u = 1;
for($i = 2; $i <= $halfHax; $i++){
echo $row[$u].'<br>';
$u++;
}
}
this is giving me all the result where Owner == $owner
just like it should, but I would like the column names to list with those, I could hard-code it out, but more columns may be added/changed so I would rather not. Any ideas?
$query = query("DESC YourTable"); $col_names = array_column($query, 'Field'); That returns a simple array of the column names / variable names in your table or array as strings, which is what I needed to dynamically build MySQL queries.
USE db_name; DESCRIBE table_name; it'll give you column names with the type.
We can verify the data in the table using the SELECT query as below. We will be using sys. columns to get the column names in a table. It is a system table and used for maintaining column information.
Try:
SHOW COLUMNS FROM mytable
http://dev.mysql.com/doc/refman/5.0/en/show-columns.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With