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

如何在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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化