【发布时间】:2014-01-12 18:15:05
【问题描述】:
我正在尝试在 PHP 中创建一个不需要精确搜索的搜索功能,即如果您搜索“mar”,它将返回“mark”和“mary”。
到目前为止,我有以下查询,但它没有达到我的预期。
$query = $this->db->prepare("SELECT * FROM `visitors` WHERE `first_name` LIKE ? OR `last_name` LIKE ? OR `phone` LIKE ? OR `email` LIKE ? or `spouse` LIKE ? OR `spousephone` LIKE ? OR `spouseemail` LIKE ? OR `child1name` LIKE ? OR `child2name` LIKE ? OR `child3name` LIKE ?");
这是我创建的函数的完整代码,也许有人可以建议正确的编写方法,因为我是 PHP 和 MySQL 的菜鸟。
public function visitor_search($search_query) {
$query = $this->db->prepare("SELECT * FROM `visitors` WHERE `first_name` LIKE ? OR `last_name` LIKE ? OR `phone` LIKE ? OR `email` LIKE ? or `spouse` LIKE ? OR `spousephone` LIKE ? OR `spouseemail` LIKE ? OR `child1name` LIKE ? OR `child2name` LIKE ? OR `child3name` LIKE ?");
$query->bindValue(1, $search_query);
$query->bindValue(2, $search_query);
$query->bindValue(3, $search_query);
$query->bindValue(4, $search_query);
$query->bindValue(5, $search_query);
$query->bindValue(6, $search_query);
$query->bindValue(7, $search_query);
$query->bindValue(8, $search_query);
$query->bindValue(9, $search_query);
$query->bindValue(10, $search_query);
try {
$query->execute();
} catch(PDOException $e){
die($e->getMessage());
}
return $query->fetchAll();
}
【问题讨论】:
-
您需要将每个
?的值包装在%mar%中,或者如果您只想匹配开头,则只需mar%。