RSS

  • YouTube
  • LinkedIn
  • Google

Archives for : Search terms

Binding several values in PDO SQL Statement (PDOStatement)

Sometimes we need to search a single value through several columns when building SQL instructions.

Suppose the table below

  • [ENTITY_ONE]
    • ID
    • COLUMN_A
    • COLUMN_B
    • COLUMN_C
    • COLUMN_D
    • COLUMN_E

If we need search a single value on columns B,D and E we will need use the following instruction

In PHP code we can do

Well, this can work but we know that isn’t the best approach. We need use Binding Values to avoid SQL injection and other malicious treats.

So, the code can be modified to

Much better, but, when building complex SQL instruction, things can be confusing with lots of arguments and don’t forget: ORDER MATTERS.

Happily PDO can bind values in different order when using named bindings.

Hmm, seems that this isn’t good enough. We only change the use of 1-indexed placeholder to a :named placeholder. There’s no gain beyond of code readable and the possibility to bind in any order.

Yes, but now we can do the best approach when using one unique search term in several columns. We can use only one bind to one or more :named placeholders ’cause PDO is smart and clever. Look our final code here.

Can save a lot of typing when writing many SQL instruction using same argument.