Note that there are some explanatory texts on larger screens.

plurals
  1. POPDO binding values for MySQL IN statement
    primarykey
    data
    text
    <p>I have an issue with PDO that I'd really like to get an answer for after being plagued by it for quite some time.</p> <p>Take this example:</p> <p>I am binding an array of ID's to a PDO statement for use in a MySQL IN statement.</p> <p>The array would be say: <strong>$values = array(1,2,3,4,5,6,7,8);</strong></p> <p>The database-safe variable would be <strong>$products = implode(',' $values);</strong></p> <p>So, <strong>$products</strong> would then be a <em>STRING</em> with a value of: <strong>'1,2,3,4,5,6,7,8'</strong></p> <p>The statement would look like:</p> <pre><code>SELECT users.id FROM users JOIN products ON products.user_id = users.id WHERE products IN (:products) </code></pre> <p>Of course, <strong>$products</strong> would be bound to the statement as <strong>:products</strong>.</p> <p>However, when the statement is compiled and values bound, it would actually look like this:</p> <pre><code>SELECT users.id FROM users JOIN products ON products.user_id = users.id WHERE products IN ('1,2,3,4,5,6,7,8') </code></pre> <p>The problem is it is executing everything inside of the IN statement as a single string, given that I've prepared it as comma-separated values to bind to the statement.</p> <p>What I actually need is:</p> <pre><code>SELECT users.id FROM users JOIN products ON products.user_id = users.id WHERE products IN (1,2,3,4,5,6,7,8) </code></pre> <p>The only way I can actually do this is by placing the values within the string itself without binding them, however I know for certain there has to be an easier way to do this.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload