How to compare Mysql to an array?

Asked

Viewed 533 times

4

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

For example:

I have a array whole-assed:

$inteiros = array();

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

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

There is the possibility of making such a comparison?

3 answers

4


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

$inteiro = array(10,3,12);
$sql = 'SELECT * FROM turma WHERE idTurma IN('. implode($inteiros, ',') .')';
  • Perfect. It worked!!!

2

Use IN.

$sql = 'SELECT * 
          FROM `table` 
         WHERE `id` IN (' . implode(',', array_map('intval', $array)) . ')';

0

Response 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.