2013-07-14 53 views
0

我使用PDO作爲pgsql數據庫。該查詢不起作用。我想問題是關於我做查詢的逗號。類似的查詢可以直接在pgAdminIII中正常工作。我嘗試過形成這個查詢的不同變體,但結果是相同的'找不到'。PDO LIKE與查詢中的參數沒有結果

// 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

'''''s1''' - 這是幹什麼用的?您需要閱讀如何正確綁定準備好的語句 –

+0

這是多種變體之一。我想搜索這個字符串$ s1。我被試過了,只有'$ s1',''s1''。 – vili

+0

我屏蔽了引號,因爲我想用LIKE來查詢這個'LIKE'%$ search_string%' – vili

回答

2

下面是一個SQLite數據庫的一個自包含例如正在建設中,然後與從$_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 */ 
} 

傳來LIKE值查詢您可以看到我選擇了周圍添加搜索詞的通配符在PHP方面;如果你想讓客戶端做到這一點,你也可以做到這一點。