How can I get mysql table column names

DECIDED I used the answer from alfasin, but since it gave me too much information, I wrote a little script to just get the field names. Since the field names looked at first, it was pretty 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 a new aray $herecontaining column names, hope this helps someone in the future :)

original question: Let me explain a bit, I have a mysql table and I'm trying to select * from it and display the result in the html list <ol>. I can get JUST FINE string data. but I can't for the life of me figure out how to grab the column names of the table to match them with the row, respectively. this is my code that captures string 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++;
      }
   }

, Owner == $owner , , , , , /, . ?

+5
3
+3

, . :

$sql = "SELECT DISTINCT * FROM User WHERE Owner = :owner";
$sth = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':owner' => $owner);

while($row=$sth->fetch(PDO::fetch_assoc) as $row) {
  //split array in half
  $hax = count($row);
  $halfHax = $hax / 2;
  //set up a for loop to give results
  foreach ($row as $key => $value) {
    echo $key.'='.$value.'<br />';
  }

}

:

array_keys($row);
+3

, SHOW COLUMNS MySQL, .

But I would suggest using mysqli_fetch_assoc and then using foreach (array_expression as $ key => $ value) to get the column name and its value for each row.

+2
source

All Articles