我有这样的数据库: 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"> </td>
</tr>
<?php } ?>
</table>
但我不知道如何显示值所在的字段名称。
答案 0 :(得分:2)
使用评论中的代码(虽然我建议使用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";
}