What is the correct syntax, if possible, to pass an array as a parameter, using FIND_IN_SET
more or less on this idea:
SELECT c.cpf FROM tbl_cliente as c WHERE FIND_IN_SET(array, c.cpf);
What is the correct syntax, if possible, to pass an array as a parameter, using FIND_IN_SET
more or less on this idea:
SELECT c.cpf FROM tbl_cliente as c WHERE FIND_IN_SET(array, c.cpf);
The function FIND_IN_SET()
searches for one (first parameter) into a list of comma-separated elements declared in another String (second parameter).
Example:
mysql> SELECT FIND_IN_SET('b','a,b,c,d');
-> 2
So if your array
is a String with elements separated by commas, use it as follows:
SELECT c.cpf FROM tbl_cliente as c WHERE FIND_IN_SET(c.cpf, array);
or
SELECT c.cpf FROM tbl_cliente as c WHERE FIND_IN_SET(c.cpf, 'cpf1,cpf2,cpf3');
On the other hand, if you have a table with CPFs and want to check if the customer's CPF is in this table, use the IN
clause, which accepts comma-separated value lists or a subselect. Example:
SELECT c.cpf FROM tbl_cliente as c WHERE c.cpf in ('xxx.xxx.xxx-xx', 'yyy.yyy.yyy-yy')
Or:
SELECT c.cpf FROM tbl_cliente as c WHERE c.cpf in (select cpf from tbl_outratabela)
A solution with php would be to generate a query with several ?
for IN()
. and then pass the cpfs in the PDO execute ()
$sql ='SELECT c.cpf FROM tbl_cliente as c WHERE c.cpf IN(';
$qtd_cpfs = count($cpfs);
$in = str_repeat('?', $qtd_cpfs);
$in = preg_replace('/,$/', '', $in);
$sql .= $in .')';
//depois
$stmt = $db->prepare($sql);
$stmt->execute($cpfs);