2

I am writing an SQL query. I have an array of unknown length and I want to select the data fromMySQL by using that array in the WHERE clause of the query. This is my query right now and it is working fine

$sql = "SELECT DISTINCT messagesutou.SenderID from messagesutou where (messagesutou.SenderID !='$items[1]' AND messagesutou.SenderID !='$items[0]' AND messagesutou.SenderID !='$items[2]') AND messagesutou.RecieverID='$uid'";

But in this I know the length of array ( 3) and I just used the array name with index for testing purpose. Now i want to know if array length is unknown then how would I write this query?

Martin
  • 22,212
  • 11
  • 70
  • 132
Umar Ghaffar
  • 121
  • 1
  • 13

1 Answers1

3
$list = implode(',', $items);

and

SELECT DISTINCT SenderID 
FROM messagesutou 
WHERE 0 = FIND_IN_SET(SenderID, '$list')
  AND RecieverID='$uid'

or (taken from Jens's answer which was deleted by him)

SELECT DISTINCT SenderID 
FROM messagesutou 
WHERE SenderID NOT IN ($list)
  AND RecieverID='$uid'

The difference - both variants are applicable when SenderID and $items values have a numeric type, only the former when they have string type, none when they have string type and contain commas or ticks.

But the latter may be adapted:

$list = '\''.implode('\',\'', $items).'\'';

and

SELECT DISTINCT SenderID 
FROM messagesutou 
WHERE SenderID NOT IN ($list)
  AND RecieverID='$uid'

It now acccepts any datatype and allows commas (but not ticks - they must be quoted before imploding).

Akina
  • 39,301
  • 5
  • 14
  • 25