【问题标题】:Search using multiple parameters, LIKE, ORDER BY使用多个参数搜索,LIKE、ORDER BY
【发布时间】:2019-01-07 11:14:41
【问题描述】:

我想为我的网站创建一个搜索表单,并能够通过选择多个参数、使用 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 radionew radio 2new radio 3。当我搜索一个术语时,例如“新”,所有三行都会显示,很好。如果我按 postCountryID 搜索,例如“3”只显示一行,也很好,因为只有一个分配给 id 3。但是当我同时搜索时,postName“new”和 postCountryID“3”没有显示结果。如何解决这个问题?显示对应于 postName 和 postCountryID 的行。在 phpMyAdmin 中工作,但使用搜索表单不起作用:

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

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

【问题讨论】:

  • 你试过用引号封装postName LIKE :searchRadioName吗?我倾向于不使用命名占位符,仅使用带有查询的 ? 占位符,所以我不确定将其更改为 postName LIKE ':searchRadioName' 是否会产生您预期的输出。
  • 是的,SQL 看起来是正确的。也许“3”没有绑定为int?特别是因为 PHP 中的 HTML 表单数据始终是一个字符串,除非您明确地将其转换为其他内容。
  • @Dominic 无论哪种方式,将其转换为正确的数据类型始终是最佳实践,$params[':postCountryID'] = $_POST['postCountryID'] 应该是 $params[':postCountryID'] = (int) $_POST['postCountryID'] - 指出得很好,但我认为这不会导致意外行为。
  • 谢谢@Jaquarh。另外,我倾向于使用$stmt-&gt;bindParam($param, $value, \PDO::PARAM_INT);(或适当的数据类型 PDO 常量)。
  • 尝试将 '%'.$_POST['postRadioName'].'%' 更改为 "'%{$_POST['postRadioName']}%'" - 当您将值绑定到占位符时,这将包含引号。

标签: php pdo sql-order-by sql-like


【解决方案1】:

$stmt-&gt;bindParam($param, $value); 替换为$stmt-&gt;bindValue($param, $value); 后,代码按预期工作。为术语“新”和国家/地区 ID = 3 检索一个结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    相关资源
    最近更新 更多