-2

How do I return the column name in mysqli by row?

...
$result = $mysqli->query("SELECT * FROM `xtdf` WHERE posterid='bike'"); 
$rows=mysqli_fetch_array($result); 

foreach($rows as $column => $value) {
    echo $column . " " . $value;
}
...

This code above will return all columns name and values, but I want only the column name by the value. I have tried this code below but returns nothing.

...
$result = $mysqli->query("SELECT * FROM `xtdf` WHERE posterid='bike'"); 
$rows=mysqli_fetch_array($result); 

foreach($rows as $column => $value) {
if ($value == "bike") {
    echo $column;
    }
}

Edit: I don't want put the result in array, or bring all results. Only return one value. PHP version: 5.5.15
What should I do?

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
John Wiky
  • 19
  • 5
  • Possible duplicate of [MySQL query to get column names?](https://stackoverflow.com/questions/4165195/mysql-query-to-get-column-names) – Ahmet Zeybek Apr 13 '18 at 21:15
  • It isn't. I don't want return ALL tables to array. I want only one without array. – John Wiky Apr 13 '18 at 21:20
  • 1
    if I understand you correctly you want to know in which column you have the value 'bike'. But in the query you ask already for `posterid` to be 'bike' - so this would be the column, right? This sounds like an XY Problem to me. What is the actual goal you wanna achieve? – Jeff Apr 13 '18 at 21:57
  • At this moment I still practicing, but in the future I'll use a loop, so is this the main reason for get the column name – John Wiky Apr 13 '18 at 22:01

1 Answers1

2

This should do the trick

while($row=mysqli_fetch_array($result)) {
    foreach($row as $column => $value) {
       if ($value == "bike") {
          echo $column;
       }
    }
}

You need to iterate through all values that you fetch from database.

Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29