douza6300 2017-12-19 15:41 采纳率: 0%
浏览 70
已采纳

如何在SELECT FROM PDO Prepared Statement中为搜索框设置多个搜索条件?

I have a prepare statement that finds the search criteria against my database which has an Articles table and Text and Title columns inside of it.

$stmt = $pdo->prepare('SELECT * FROM articles WHERE text OR title LIKE :search');

My problem is that the statement only searches by title and completely ignores text.

I tried it like so and it works but I also need title

$stmt = $pdo->prepare('SELECT * FROM articles WHERE text LIKE :search');
  • 写回答

1条回答 默认 最新

  • doujunchi1238 2017-12-19 15:51
    关注

    You can use the same placeholder as many times as you want *. You just have to use proper SQL syntax. See below:

    $stmt = $pdo->prepare('SELECT * FROM articles WHERE text LIKE :search OR title LIKE :search');
    //                                                       ^^^^^^^^^^^^
    

    And then just bind once to it:

    $stmt->bindValue(':search', $searchTerm); // replace $searchTerm with your variable name
    

    The value will fill both places.

    I assume you're already adding % to the variable you're binding.


    * From PDO::prepare:

    You cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.

    So, as long as emulation mode is on, you're good to go. Otherwise, you'd have to name and bind them separatelly:

    $stmt = $pdo->prepare('SELECT * FROM articles WHERE text LIKE :search1 OR title LIKE :search2');
    $stmt->bindValue(':search1', $searchTerm);
    $stmt->bindValue(':search2', $searchTerm);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?