简体   繁体   中英

Retrieving column name based on user input in MYSQL using php

Currently i am doing a PHP GET and getting values after clicking the submit button.

I got the values out from the submit button but I dont know how to reference them to the values in column.

For example, after clicking the submit button, I get the value 1.

Inside my database i have 3 columns

Col 1 Col 2 Col 3

 2   3  1

How do i get the COLUMN name by just having the value itself? Thank you so much!

Ugly/silly, but would do what you want:

Query:

SELECT * FROM yourtable WHERE 1 in (col1, col2, col3, ... ,colN)

and then manually pick out the value in client code:

$row = mysql_fetch_assoc($result);
$matches = array_search(1, $row);
var_dump($matches);

You can't get away from listing all of the columns in the query, because there's no WHERE x IN (*) -type construct.

I would do it like this.

Get all table columns

then loop throug results and run select for each column

$columnVsValue = array();

foreach($columns as $column) {
  $q = "SELECT id FROM table where {$column} = {$value}";
  if(TRUE) { // you have to check that query return value
    $columnVsValue[] = $column;
  }
}

I did it quick probably there is more efficient way to do it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM