【发布时间】:2016-05-11 05:37:36
【问题描述】:
我正在尝试构建逻辑以创建用于 PDO 的多字 LIKE 语句。
这需要搜索字符串 $str 来构建 LIKE 部分的多个部分:
$str = $_POST['str'];
$keywords = preg_split('/[\s]+/', $str);
$totalKeywords = count($keywords);
$search = "%$str%";
$sql_str = " AND post_content LIKE :search0 ";
for($i=1 ; $i < $totalKeywords; $i++){
$search_bit = ":search" . $i;
$sql_str .= " AND post_content LIKE $search_bit ";
}
这是 SQL 语句 - 将 $sql_str 插入正确的位置:
$sql = "SELECT d.ID
, d.post_date
, d.post_content
, d.post_cat_id
, d.post_label
, c.fld_cat
FROM tbl_log_days d
, tbl_log_cats c
WHERE d.post_cat_id = c.fld_id " . $sql_str . "
ORDER BY post_date";
然后为了绑定变量,我尝试了两种方法:
$stmt = $pdo->prepare($sql);
if (!empty($sql_str)) {
foreach ($keywords as $key => &$keyword){
$foo = '%'.$keyword.'%';
$stmt->bindParam(':search' . $key, $foo);
}
}
还有这个(在 foreach 行中 $keyword 之前没有和号):
$stmt = $pdo->prepare($sql);
if (!empty($sql_str)) {
foreach ($keywords as $key => $keyword){
$foo = '%'.$keyword.'%';
$stmt->bindParam(':search' . $key, $foo);
}
}
但是,当我搜索例如“过去的山”并检查实际运行的结果 SQL(我在 MySQL 中启用了查询日志记录),它只需要搜索字符串中的最后一个单词:
SELECT d.ID
, d.post_date
, d.post_content
, d.post_cat_id
, d.post_label
, c.fld_cat
FROM tbl_log_days d
, tbl_log_cats c
WHERE d.post_cat_id = c.fld_id AND post_content LIKE '%past%' AND post_content LIKE '%past%'
ORDER BY post_date
我在运行搜索时对 $keyword 变量进行了 var_dump,它返回:
string(4) "hill"
string(4) "past"
我无法解决这个问题。有可能做我想做的事吗?
【问题讨论】: