【问题标题】:Using LIKE Wildcard is causing random characters使用 LIKE 通配符会导致随机字符
【发布时间】:2018-08-27 05:42:36
【问题描述】:

我有一个带有如下查询的 php 脚本:

$b = $a[0];  // 2115
$c = $a[1];  // 2197
$sql = "SELECT DISTINCT a.document_id 
        FROM archive_locations a 
        INNER JOIN archive_locations b 
           ON (a.document_id = b.document_id) 
           AND 
           (
              a.street_address LIKE '%$b%' 
              OR a.location_name LIKE '%$b%' 
           )
           AND 
           (
              b.street_address LIKE '%$c%' 
              OR b.location_name LIKE '%$c%' 
           )
           ORDER BY a.document_id;";

但是当我回显这个查询时,我得到了这个:

SELECT DISTINCT a.document_id 
FROM archive_locations a 
INNER JOIN archive_locations b 
   ON (a.document_id = b.document_id) 
   AND 
   (
      a.street_address LIKE '%!15%' 
      OR a.location_name LIKE '%!15%' 
   )
   AND 
   (
      b.street_address LIKE '!97%' 
      OR b.location_name LIKE '!97%' 
   )
   ORDER BY a.document_id;

似乎是字符% 导致了这个问题。我尝试转义它,但一定有一些我不知道的特殊转义或模式需要。我可以使用一些帮助。谢谢!

【问题讨论】:

  • 使用参数。不要使用查询字符串。
  • @Gordon Linoff - 请举例。

标签: php postgresql wildcard sql-like


【解决方案1】:

您可以在变量名前后使用花括号,例如 {}

$sql = "SELECT DISTINCT a.document_id 
        FROM archive_locations a 
        INNER JOIN archive_locations b 
           ON (a.document_id = b.document_id) 
           AND 
           (
              a.street_address LIKE '%{$b}%' 
              OR a.location_name LIKE '%{$b}%' 
           )
           AND 
           (
              b.street_address LIKE '%{$c}%' 
              OR b.location_name LIKE '%{$c}%' 
           )
           ORDER BY a.document_id;";

何时使用花括号:

当您在字符串中定义变量时,PHP 可能会混淆 如果使用简单的语法来定义一个带有其他字符的变量 变量,这将产生错误

查看更多:When to wrap curly braces around a variable

【讨论】:

  • 我已经尝试过了,不幸的是它不起作用。结果相同。
  • 如果它不适合你,那么你也可以像这样尝试LIKE '%" . $a. "%'"。让我知道这是否有效?
  • 我正在使用 postgresql
  • 我知道你使用的是 postgresql 但没有 php?
  • 不,我使用的是 php 7。pg_escape_string 也不起作用
猜你喜欢
  • 2013-05-15
  • 1970-01-01
  • 2017-09-20
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多