【问题标题】:PDO LIKE with parameter in query doesn't have result查询中带有参数的 PDO LIKE 没有结果
【发布时间】:2013-07-14 21:26:29
【问题描述】:

我将 PDO 用于 pgsql 数据库。查询不起作用。我想问题出在我进行查询的逗号上。类似的查询可以直接在 pgAdminIII 中正常工作。我尝试了形成此查询的不同变体,但结果是相同的“未找到”。

// Get Search
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $conn->quote($search_string);
echo $search_string;
$s1 = '%'.$search_string.'%';


// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
    // query

$query =  $conn->prepare('SELECT title FROM book WHERE author LIKE ?');
$query->bindValue(1, '\'$s1\'', PDO::PARAM_STR);
    $query->execute();

    if (!$query->rowCount() == 0) {
        while ($results = $query->fetch()) {
            echo $results['title'] . "<br />\n";
        }
    } else {
        echo 'Nothing found';
    };

【问题讨论】:

  • '\'$s1\'' - 这是干什么用的?您需要阅读如何正确绑定准备好的语句
  • 这是多种变体之一。我想搜索这个字符串 $s1。我试过了,只有$s1'$s1'
  • 我屏蔽引号,因为我想用 LIKE 像这样LIKE '%$search_string%'进行查询
  • 不要“尝试”“变体”。 完全按照您在准备好的语句教程中阅读的内容进行操作。

标签: pdo parameters sql-like


【解决方案1】:

这是一个正在构建的 SQLite 数据库的自包含示例,然后使用来自 $_POST 的 LIKE 值进行查询

<?php

$_POST['searchterm'] = 'King';      /* This is just for demonstration */


/* Create our database first */
$books = array(
        array(':id' => 0, ':author' => 'J. R. R. Tolkien', ':title' => 'The Lord of the Rings: The Fellowship of the Ring',),
        array(':id' => 1, ':author' => 'J. R. R. Tolkien', ':title' => 'The Lord of the Rings: The Two Towers',),
        array(':id' => 2, ':author' => 'J. R. R. Tolkien', ':title' => 'The Lord of the Rings: The Return of the King',),
);

$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $pdo->exec('CREATE TABLE books(id int, title varchar(255), author varchar(255))');
$stmt = $pdo->prepare('INSERT INTO books(id, title, author) values(:id, :title, :author)');
try {
        foreach($books as $book) $stmt->execute($book);
} catch (PDOException $e) {
        echo $e;
}

$stmt = $pdo->prepare("select * from books where title LIKE :search");

if (! $stmt->execute(array(':search' => '%'.$_POST['searchterm'].'%'))) {
        /* No matches, you should do something intelligent about it */
}
foreach($stmt->fetchAll(PDO::FETCH_BOTH) as $row) {
        var_dump($row);  /* For demo only; not practical in the real-world */
}

您可以看到我选择在 PHP 端的搜索词周围添加通配符;如果你想让客户端这样做,你也可以这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    相关资源
    最近更新 更多