使用LIKE、ORDER BY等多个参数进行搜索



我想为我的网站创建一个搜索表单,并能够通过选择多个参数进行搜索,使用LIKE并最终使用ORDER by。按名称、国家和日期进行搜索。

InnoDB,排序规则utf8mb4_unicode_ci,php 5.6

<?php
if(isset($_POST['search'])){
$sql = 'SELECT * FROM radio_posts';
$where = array();
$params = array();      
if (!empty($_POST['postRadioName'])) {
$where[] = "postName LIKE :searchRadioName";
$params[':searchRadioName'] = '%'.$_POST['postRadioName'].'%';
}
if (!empty($_POST['postCountryID'])) {
$where[] = "postCountryID = :postCountryID";
$params[':postCountryID'] = $_POST['postCountryID'];
}

if (!empty($where)) {
$sql .= ' WHERE (' . implode(') AND (', $where) . ') ' ;
}
$stmt = $db->prepare($sql);
foreach($params as $param => $value) {
$stmt->bindParam($param, $value);
}
$stmt->execute();    
}
?>

我的表是radio_posts,还有一些列,postID、postName、postCountryID、postDate。在postName中,我有几行:新电台第二台新电台第三台新电台。当我搜索一个术语时,例如"new",所有三行都会显示出来,很好。如果我按postCountryID搜索,例如"3",只显示一行,这也很好,因为只有一行被分配给id 3。但当我同时搜索postName"new"和postCountryID"3"时,不会显示任何结果。如何解决这个问题?显示postName和postCountryID对应的行。在phpMyAdmin中可以工作,但使用搜索表单不起作用:

SELECT * FROM `radio_posts` WHERE postName LIKE '%new%' AND postCountryID = 3

此外,如果可能的话,我想问一下,按postDate列升序和降序排列结果的最佳方法是什么。

$stmt->bindValue($param, $value);替换$stmt->bindParam($param, $value);后,代码按预期工作。检索到一个术语"新"和国家ID=3的结果。

最新更新