Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

7
  • Why is it needed to do *2-1 rather than just -1 on the count()? Commented Apr 17, 2013 at 11:53
  • 1
    @Nalum: Because str_pad's 2nd parameter is the "pad length" which is in characters. Since you want a question mark for each value and a comma in between them, that works out to be count($values)*2-1. You could alternatively use something like str_repeat('?,',count($values)-1).'?' if you want. Commented Jun 3, 2013 at 8:54
  • 3
    I prefer to use implode(',', array_fill(1,count($values),'?')) because there's less chance of off-by-one errors, and you don't have to handle the last element differently. Commented Feb 13, 2014 at 19:35
  • 2
    you can also use str_repeat() for this, it's probably the most efficient of the listed methods: rtrim( str_reapeat('?,', count($values)), ',') Commented Jul 24, 2014 at 6:47
  • 1
    @Dominique You are reading the code wrong. It does not put variables directly inside the query. That is really the point of the solution. It puts a "?" for every variable so that PDO can prepare the actual statement. Yes we like PDO's safeguards, and this solution presents a way to use them. Commented Nov 6, 2015 at 17:17