获取在MySQL中找到数据的列名

Ari*_*ies 1 php mysql pdo

是否有可能获得列名称,其中找到特定数据而不通过结果循环,可能是PDO?或者在mySQL中有另一种方法吗?

该示例仅显示3列,但对于我的表,我可能需要检查多达30列

如果我有一个表table1,并想找到找到'x'的列

+----+------+------+------+
| id | Col1 | Col2 | Col3 |
+----+------+------+------+
|  0 | x    | b    | x    |
|  1 | x    | x    | f    |
|  2 | d    | x    | g    |
|  3 | h    | j    | k    |
+----+------+------+------+
Run Code Online (Sandbox Code Playgroud)

currentyl我运行一个Select然后循环到每一行并检查每一行是否数据是'x'

$query= "SELECT * FROM table1 WHERE (Col1='x' OR Col2='x' OR Col3='x')"
$result=mysql_query($query);
$foundCols = array();
$rowCnt = 0;
while ($row = mysql_fetch_assoc($result)) {
  $tmpArr = array();
  if ($row['Col1'] == 'x') {
     $tmpArr[] = 'Col1';
  }
  if ($row['Col2'] == 'x') {
     $tmpArr[] = 'Col2';
  }
  if ($row['Col3'] == 'x') {
     $tmpArr[] = 'Col3';
  }
  $foundCols[$rowCnt] = $tmpArr;
  $rowCnt = $rowCnt+1
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Pet*_*tah 5

试试这个:

while ($row = mysql_fetch_assoc($result)) {
    ...
    foreach (array('Col1', 'Col2', 'Col3') as $key) {
        if ($row[$key] == 'x') {
            $tmpArr[] = $key;
        }
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)