V
V
Valera Dobroman2022-02-15 12:12:14
PHP
Valera Dobroman, 2022-02-15 12:12:14

How to replace a string with numbers in the IN operator?

I need to take an array of users except id 8,10,11 and so on
. My query looks like this:

SELECT *
    FROM `users`
    WHERE id not in(?)

And the problem is "id not in(?)"
The fact is that in PHP I have an array [8,10,11] which I concatenated with a comma to get the string => "8,10,11" ,
nothing smart without thinking, I shove this line into IN, performing the following action ...->execute(["8,10,11" ]);
The 8th id is not shown properly, but obviously 10 and 11 dude got in my party (showed up)
I understand that there should be numbers in IN, but how can I convert a line with 3 or more digits into a normal int ?
So that in the end sql would get something like this: id not in(8,10,11) ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FanatPHP, 2022-02-15
@Valera221

The numbers here are just completely optional, but there should be more question marks. For every go.
PHP is not a genie out of a bottle to guess what was meant here - the whole string or individual values.
If you need separate values, then you need to transfer them separately , n'est pas?
It certainly doesn't look as pretty, but there are still no other options.

$array = [8,10,11]; 
$in  = str_repeat('?,', count($array) - 1) . '?';
$sql = "SELECT * FROM users WHERE id NOT IN ($in)";
$stmt  = $db->prepare($sql);
$stmt->execute($array);

A
Akina, 2022-02-15
@Akina

If the passed parameter is a CSV of identifiers, then you should use

SELECT *
FROM `users`
WHERE FIND_IN_SET(id, ?);

Note 1. CSV should not contain any parasitic spaces (otherwise all sorts of "decorators" like to poke spaces after the comma).
Note 2. Such a request is a guaranteed fullscan. But there will be no injection.
PS. In principle, this CSV is easy to bring to the JSON array state (just add two brackets) - then you can use JSON_CONTAINS(), which can be a little faster. And if the transmitted JSON is parsed into separate values ​​using JSON_TABLE (), we will also get rid of the fullscan (however, the server version is needed quite fresh).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question