0

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

1 回答 1

2

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

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

于 2013-07-15T18:06:38.403 回答