3

I have a code :

$id=implode(",",$selected);

$query = "SELECT u.id, p.brand, n.number FROM `user` u 
LEFT OUTER JOIN `phone` p ON u.id = p.id LEFT OUTER JOIN `number` n 
ON p.id = n.id WHERE u.id in ($id)";

Where $selected is an array array(1,2,3). But when i run it, it appears this notice :

Unknown column '1' in 'where clause'

How to handle this problem? Thank you

  • 5
    `echo $query;` What is it? – u_mulder May 12 '16 at 19:27
  • 2
    It's giving you `u.id in (1,2,3)`. In SQL usually numbers are understood as column numbers, for values you need `'1','2','3'` and then Hemant's answer makes sense there. And then there's the security flaw McAdam commented about: you are not using parameterized queries. – SparK May 12 '16 at 19:47

1 Answers1

1

Here you can do it like :

$id = implode("','",$selected);

This query will run :

$query = "SELECT u.id, p.brand, n.number FROM `user` u LEFT OUTER JOIN `phone` p ON u.id = p.id LEFT OUTER JOIN `number` n 
ON p.id = n.id WHERE u.id in ('$id')";
Hemant Sharma
  • 75
  • 1
  • 7
  • I understand that you're trying to demonstrate how the `IN` clause should be used, but this doesn't help the OP who is trying to do it using a parameterized query. – AdamMc331 May 12 '16 at 19:37
  • @McAdam331 It actually does help him, his problem is not using quotes around the values, so `1` (the first array value) is interpreted as a column name and not a value. With that said, he should probably consider using prepared statements or at a minimum sanitizing the input values. – Juan May 12 '16 at 19:50
  • @Juan That makes sense now that you've explained it to me, but the answer may not have been intuitive to a newbie (since it wasn't intuitive to me), so it could be edited to explain that. – AdamMc331 May 12 '16 at 19:52
  • I have fixed the query for the question. – Hemant Sharma May 12 '16 at 19:54
  • Hello, i tried your suggestion but it still give an error, so i add '' in `('$selected')` part, thank you ;) – Kirari Akito May 13 '16 at 00:14