PDO LIKE与查询中的参数没有结果

时间:2013-07-14 21:26:30

标签: pdo parameters sql-like

我将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';
    };

1 个答案:

答案 0 :(得分:2)

以下是正在构建的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端的搜索词周围添加通配符;如果你想让客户端这样做,你也可以这样做。