-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?

  • 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. – user2864740 Jan 11 '20 at 19:59
  • https://stackoverflow.com/q/13962266/2864740 , https://stackoverflow.com/a/22891756/2864740 , https://stackoverflow.com/a/17874410/2864740 – user2864740 Jan 11 '20 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);` – Tim Morton Jan 11 '20 at 20:05
  • 1
    @TimMorton (The links above show how to generate such a N-value dynamic string *and* safely bind..) – user2864740 Jan 11 '20 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.* – IncredibleHat Jan 11 '20 at 20:09
  • yep, didn’t see your comment until after I commented. (I type slowly on the phone)... – Tim Morton Jan 11 '20 at 20:09
  • Thanks a lot folks! Really appriciate your help a lot! – diforat Jan 11 '20 at 20:13
  • Ugh, I flipped explode and implode... @IncredibleHat while technically true, in practice I disagree because (as I just demonstrated) even programmers can’t always be trusted! – Tim Morton Jan 11 '20 at 20:21

1 Answers1

-1

Before inserting in query convert array to string.

$data = implode(','$data);
Abhishek Honrao
  • 780
  • 5
  • 28
  • Please close duplicate questions instead of answering them so that the system can automatically purge the redundant content from this site. – mickmackusa Nov 21 '20 at 12:03