php - 根据值显示数据库字段名称

标签 php mysql

我有这样的数据库: The database is have same value (matthew) but in different fields

我想使用 HTML 和 PHP 制作一个搜索框,当我输入“matthew”时,它显示如下: when i search 'matthew' it's show like this

我的问题是使用什么查询来选择此值并显示“matthew”值所在的字段名称?

这是我的小代码:

<?php
$search='matthew';
$sql = mysql_query("select * from test where test.field_1 like '%$search%' or test.field_2 like '%$search%' or test.field_3 like '%$search%' order by id");
?>

<table width="200" border="1">
  <tr>
    <td align="center"><b>Name</b></td>
    <td align="center"><b>Field</b></td>
  </tr>
<?php
while ($data=mysql_fetch_array($sql))

{ ?>  
  <tr>
    <td align="center"><?php echo $data['name']; ?></td>
    <td align="center">&nbsp;</td>
  </tr>
<?php } ?>
</table>

但我不知道如何显示值所在的字段名称。

最佳答案

使用评论中的代码(尽管我建议使用 PDO,因为 mysql_* 已被弃用且不安全)

$sql = mysql_query("select * from test where test.field_1 like '%$search%' or test.field_2 like '%$search%' or test.field_3 like '%$search%'");

// i don't remember how fetching works in mysql_, i think something like this..
$results = mysql_fetch_assoc($sql);

foreach($results as $column_name => $value){
    // check for the string
    if(strpos($value, "mike") === false) continue; // or whatever, use the variable that contains the searched text instead of "mike"

    echo "result was found in the $column_name column. The full value of that column is $value";
}

关于php - 根据值显示数据库字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34521933/

相关文章:

php - CakePHP:连接表数据未显示在 View 中

javascript - 分离 PHP 和 Javascript 代码的最佳方法

php - 通过 PHP 中的 SendGrid 以编程方式发送电子邮件(批量电子邮件)

php - 按行显示图像

php - 使用 htmlentities 获取 €

mysql - 加入2个一对多关系

mysql - View 选择不能包含 from 子句

PHP cookie 在注销时不会删除

php - 如果输入有一个或多个问号,则从数据库获取数据。

php - 本地主机渲染页面很慢