【问题标题】:LIKE Statement not Working Properly in PDOLIKE 语句在 PDO 中无法正常工作
【发布时间】:2015-04-14 19:10:04
【问题描述】:

我有这段代码可以从我的数据库中返回搜索结果:

$search_stmt = $dbConnection->prepare("SELECT * from `books` WHERE `title` LIKE '%testing1234%' ORDER BY `rating` DESC, `title` ASC LIMIT 1000");

这是我的数据库的一部分:

---------------------
| id |title         |
---------------------
| 1  |testing1234   |
---------------------
| 2  |Testament...  |
---------------------

这不会从我的表中返回任何内容。

testing1234 替换为testing,这将返回行1

我也尝试将testing1234 替换为test,这会返回两行。

我也将LIKE '%testing1234%' 替换为REGEXP 'testing1234',但我使用REGEXP 得到的结果与我使用所有LIKE 语句得到的结果相同。

当我将原始查询放入 Sequel Pro 时,它返回行 1

所以我的结论是我没有正确使用 PDO,非常感谢任何帮助我朝着正确方向前进的帮助!

【问题讨论】:

  • 如果你使用'%testing123%'会发生什么?
  • MySQL 在这里没有任何问题。见小提琴:sqlfiddle.com/#!9/fefc3/1
  • 查看PDO info 了解如何使用 LIKE
  • @JayBlanchard '%testing123%''%testing12%''%testing1%' 都没有返回任何内容。
  • 你能试试:'\%testing123\%'吗? % 可能会为准备好的查询启动一个变量名。

标签: php mysql pdo sql-like


【解决方案1】:

答案是确保在建立与数据库的连接时定义charset

这是连接的原始代码:

$dbConnection = new PDO('mysql:host=' . $db_host . ';dbname=' . $db_name . '', $db_user, $db_pass);

应该这样做:

$dbConnection = new PDO('mysql:host=' . $db_host . ';dbname=' . $db_name . ';charset=utf8', $db_user, $db_pass);

【讨论】:

    猜你喜欢
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    相关资源
    最近更新 更多