Mysqli在多个领域中搜索价值

时间:2012-04-30 20:57:48

标签: php mysql

我试图弄清楚如何搜索可能在Field1,Field2或Field3中的Value1。我知道我的语法错误,因为它显然不起作用,但这是我对它的破解:

$query = "SELECT *
   FROM table1
  WHERE city = '$city'
    AND state = '$state'
    AND location = '$location'
    AND (field1 = '$field1U' OR field1 = '$field2U' OR field1 = '$field3U')
  ORDER BY date_created LIMIT 5";
$data = mysqli_query($dbc, $query);

我想也许我可以使用(1,2,3)中的field1但我无法使用它。任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:0)

如果您想查找以下所有记录:

field1 = someValue

field2 = someValue

field3 = someValue

然后你可以使用它:

  $query = "SELECT * FROM table1 WHERE city = '$city' AND state = '$state' AND    location = '$location' AND (field1 = '$Value1' OR field2 = '$Value1' OR field3 = '$Value1') ORDER BY date_created LIMIT 5";
    $data = mysqli_query($dbc, $query);

答案 1 :(得分:0)

替换

AND (field1 = '$field1U' OR field1 = '$field2U' OR field1 = '$field3U')

AND (field1 = '$search' OR field2 = '$search' OR field3 = '$search')

(注意我正在搜索field1,field2或field3) 但是,拜托,请(!!)逃避那些$搜索字符串!例如:

$search = mysqli_real_escape_string($link, $search)

其中$ link是使用

设置的
$link = mysqli_connect(...)

请参阅http://php.net/manual/de/mysqli.real-escape-string.php 这用于防止SQL注入(https://en.wikipedia.org/wiki/SQL_injection)

哦,并尝试从变量中分割文本,就我个人而言,认为这是更安全和更好的编码风格。对于您的用例:

AND (field1 = '" . $search . "' OR field2 = '" . $search . "' OR field3 = '" . $search . "')