How to compare MySQL with an array?

4

I have to make a MySQL comparison with an array of numbers.

For example:

I have array of integers asm:

$inteiros = array();

And I have to return the ids of my class table with this array , like this:

SELECT * FROM turmas WHERE idTurma = (AQUI ENTRA O ARRAY);

Is there a possibility to make this comparison?

    
asked by anonymous 10.10.2016 / 14:47

3 answers

4

Use the implode() function to transform the array into a comma-delimited string, this goes in the IN

$inteiro = array(10,3,12);
$sql = 'SELECT * FROM turma WHERE idTurma IN('. implode($inteiros, ',') .')';
    
10.10.2016 / 14:52
2

Use IN.

$sql = 'SELECT * 
          FROM 'table' 
         WHERE 'id' IN (' . implode(',', array_map('intval', $array)) . ')';
    
10.10.2016 / 14:52
0

Reply taken from SOEn if your code is with PDO

$inteiros = array(1,2,3,4,5,6,7,8,9,10);

$qMarks = str_repeat('?,', count($ids) - 1) . '?';
$sth = $db->prepare("SELECT * FROM myTable WHERE id IN ($qMarks)");
$sth->execute($inteiros);
    
10.10.2016 / 14:54