Where in an array

Asked

Viewed 820 times

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 the same compare a id user. However, I get this id through a array, how do I make this comparison?

Array:

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

I receive these two parameters id.

  • ver isto http://stackoverflow.com/questions/907806/php-mysql-using-an-array-in-where-clause @Fred

  • this array is received by fetch_array or this array comes from somewhere else, it’s a bit confusing

3 answers

2

You can use the function IN, for more information see on ONLY or Mysql, leave an example:

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

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

1

The @Tmc answers work, but they use SQL concatenation, something I don’t think is the best way. I recommend using prepared Statements as described in this question.

Your consultation 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();

-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.";
  • 1

    This solution allows injection of SQL code. Check out this question: http://answall.com/questions/3864/como-prevenir-inje%C3%A7%C3%a3o-de-c%C3%b3digo-sql-no-meu-c%C3%b3digo-php

Browser other questions tagged

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