-1

以下代码用于从数据库中的表中搜索姓氏。用于获取搜索的字段是 'q' 这是查询

 $sims = mysql_query("SELECT * FROM electors 
WHERE constituency = '$constituency'
 AND ward = '$ward' AND (surname RLIKE '$q') LIMIT 18");

但是,如果用户输入以下任何一项或其中任何一项的任何组合以任何顺序放在一起,则该查询将不起作用,因为它仅搜索姓氏

标题,名字,首字母,姓氏,后缀,卷号,电子邮件,电话

我希望它在不重复结果的情况下从这些字段中的任何一个搜索匹配结果。

这意味着,例如,如果我输入 KNIGHT,它会找到姓 KNIGHT 的每个人,如果我输入 ROBIN KNIGHT,它会找到名字 ROBIN 和姓 KNIGHT 的任何人,反之亦然。

4

2 回答 2

0

只需将它们拆分为一个OR语句:

$sims = mysql_query("SELECT * 
                     FROM `electors` 
                     WHERE `constituency` = '$constituency' 
                     AND `ward` = '$ward' 
                     AND (`title` RLIKE '$q' 
                         OR `first_name` RLIKE '$q' 
                         OR `initial` RLIKE '$q' 
                         OR `surname` RLIKE '$q' 
                         OR `suffix` RLIKE '$q' 
                         OR `roll_no` RLIKE '$q' 
                         OR `email` RLIKE '$q' 
                         OR `telephone` RLIKE '$q') 
                     LIMIT 18");

不是最有效的查询,但它会完成工作。

此外,请确保$q在执行该查询之前进行清理。SQL注入是一个主要问题。

于 2012-06-27T09:10:45.847 回答
0
$q = str_replace(" ", "|", $q);

$sims = mysql_query("SELECT DISTINCT * FROM electors 
                     WHERE constituency = '$constituency'
                     AND ward = '$ward' 
                     AND (title RLIKE '$q'
                     OR first_name RLIKE '$q'
                     OR initial RLIKE '$q'
                     OR surname RLIKE '$q'
                     OR suffix RLIKE '$q'
                     OR roll_no RLIKE '$q'
                     OR email RLIKE '$q'
                     OR telephone RLIKE '$q')
                     LIMIT 18");

但实际上你应该使用 mysqli 和准备好的语句。

$stmt = $mysqli->prepare("SELECT DISTINCT * FROM electors 
                         WHERE constituency = ?
                         AND ward = ?
                         AND (title RLIKE ?
                         OR first_name RLIKE ?
                         OR initial RLIKE ?
                         OR surname RLIKE ?
                         OR suffix RLIKE ?
                         OR roll_no RLIKE ?
                         OR email RLIKE ?
                         OR telephone RLIKE ?)
                         LIMIT 18");
$stmt->bind_param('ssssssssss', $constituency, $ward, 
                  $q, $q, $q, $q, $q, $q, $q, $q, $q);
$stmt->execute();
于 2012-06-27T09:24:43.580 回答