Where in an array

4

I have the following Query:

SELECT u.user_nome
FROM tb_Usuario u
WHERE u.user_ativo = 1

I need one more clause where where it compares a id of the user. However, I get this id through array , how do I make that comparison?

Array :

(
  [0] => 1-funil-pr-
  [1] => 3-funil-pr-2
)

I get these two parameters id .

    
asked by anonymous 08.11.2016 / 18:31

3 answers

-1

Solved!

$recebe_do_controller = $data->recebe_do_controller; //DADOS RECEBIDOS DO CONTROLLER
$array_explode = explode(',', $recebe_do_controller); //FIZ O EXPLODE NO ARRAY PRQ PRECISEI UTILIZÁ-LO EM OUTRAS FUNÇÕES.
$array_implode = "('".implode("','", $array_explode)."')"; //IMPLODE ARRAY PARA PODER UTILIZAR AS INFORMAÇÕES NA QUERY

SELECT
 u.user_nome
FROM
 tb_Usuario u
WHERE
 u.user_ativo = 1 AND u.user_slug IN ".$array_implode.";
    
08.11.2016 / 21:07
2

You can use the IN function, for more information, see SO or MySQL , here is an example:

$array = array(1, 4, 5, 7);

$sql = 'SELECT * 
        FROM 'table' 
        WHERE 'id' IN (' . implode(',', array_map('intval', $array)) . ')';
    
08.11.2016 / 18:43
1

The @Tmc responses work, but they use SQL concatenation, which I think is not the best way. I recommend using prepared Statements as described question.

Your query can be done as follows:

$arrTokens = ["1", "18", "35"];
$qtdElementos = count($arrTokens);
$arrInterrogacoes = array_fill("0", $qtdElementos, "?");

$sql = "SELECT u.user_nome FROM tb_Usuario u WHERE u.user_ativo = 1 AND u.user_slug IN (";
$sql .= implode(",", $arrInterrogacoes);
$sql .= ")";

$statement = $suaConexaoPDO->prepare($sql);

for($i = 0; $i < $qtdElementos; $i++) {
  $statement->bindValue($i, $arrTokens[$i]);
}

$statement->execute();
    
10.11.2016 / 12:27