-1

I'm trying to make a following query:

SELECT * FROM data WHERE ID IN ('$data')

While the $data is:

Array
(
    [0] => 2
    [1] => 4
)

But the output is: "Array to string conversion"

However if I do SELECT * FROM data WHERE ID IN (2, 4) everything works!

How do I change the array to this kind of string of numbers, please?

8
  • 2
    Use placeholders. Built the SQL placeholder string dynamically (.. WHERE ID IN (?, ?) or as appropriate), then bind to each element of the array. Then the question is: "How can I turn an array of N elements into the string ?, .., where ? is repeated N times?".. IIRC, some adapters already support array-binding to multiple expansion. This problem is not novel: expand searches to look for the end problem being solved. Commented Jan 11, 2020 at 19:59
  • stackoverflow.com/q/13962266/2864740 , stackoverflow.com/a/22891756/2864740 , stackoverflow.com/a/17874410/2864740 Commented Jan 11, 2020 at 20:03
  • 1
    So the root question is how to turn [2,4] into '2,4'. In which case the answer would be explode(',',$data. But, this is unfortunately the wrong question, because that’s not the proper way to do this query. If using prepared statements in pdo, no conversion is needed: $stmt = $pdo->prepare(‘SELECT * FROM data WHERE ID IN(?,?); $stmt->execute ($data); Commented Jan 11, 2020 at 20:05
  • 1
    @TimMorton (The links above show how to generate such a N-value dynamic string and safely bind..) Commented Jan 11, 2020 at 20:06
  • If $data is not user input in anyway, but values created via code (trusted), you can bypass the complexity of a prepared statement and use implode there. If you cannot trust the values in $data, see all above. You dont have to use a prepared statement for everything, needlessly. Commented Jan 11, 2020 at 20:09

1 Answer 1

-1

Before inserting in query convert array to string.

$data = implode(','$data);
Sign up to request clarification or add additional context in comments.

1 Comment

Please close duplicate questions instead of answering them so that the system can automatically purge the redundant content from this site.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.