Reference — frequently asked questions about PDO

后端 未结 3 2115
广开言路
广开言路 2020-11-21 05:17

What is this?

This is a list of frequently asked questions regarding PHP Data Objects

Why is this?

As PDO has some features unknown to a regular

3条回答
  •  孤独总比滥情好
    2020-11-21 05:54

    How can I use prepared statements with LIKE operator?

    Prepared statement can represent complete data literal only. Not a part of literal, nor a complex expression, nor identifier. But either string or number only. So, a very common pitfall is a query like this:

    $sql = "SELECT * FROM t WHERE column LIKE '%?%'";
    

    If you ponder on this query a bit, you'd understand that being inside of single quotes, a question mark become a literal question mark, without any special meaning for the prepared statements.

    So, one have to send complete string literal using prepared statement. There are 2 possible ways:

    • either prepare FULL expression first:

      $name = "%$name%";
      $stm  = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
      $stm->execute(array($name));
      $data = $stm->fetchAll();
      
    • or use a concatenation inside the query

      $sql = "SELECT * FROM t WHERE column LIKE concat('%',?,'%')";
      

    though the latter seems too bloated.

提交回复
热议问题