How to do a select with an array? [duplicate]

0

Well, this is the following I have an array called $ posts, this $ posts array is an array that contains several things, such as: Work, Dinner, Home, Away.

What do I want to do a select to a table in the database where posto = $ posts, that is to all the results, that are in the array?

How can I do this?

Thank you.

@EDIT:

 echo $postosstring;

    $procura1 = mysqli_query($link, "SELECT * FROM faturacoes where Status = 1 AND Data >= '$datainicial' AND Data <= '$datafinal' AND posto IN ('.$postosstring.')");

    // Total Contratos

    $resultset1 = mysqli_query($link, "SELECT SUM(contratos) as contratos FROM faturacoes where status='1' AND Data >= '$datainicial' AND Data <= '$datafinal' AND posto IN ('.$postosstring.')"); 

    $linha1= mysqli_fetch_assoc($resultset1); 

    $soma1 = $linha1['contratos'];

    // Total Valor
$resultset2 = mysqli_query($link, "SELECT SUM(valor) as valor FROM faturacoes where Status = 1 AND Data >= '$datainicial' AND Data <= '$datafinal' AND posto IN ('.$postosstring.')");


$linha2= mysqli_fetch_assoc($resultset2); 

$soma2 = $linha2['valor'];

My SELECT is not working.

    
asked by anonymous 15.01.2017 / 22:00

1 answer

7

You can use IN .

If the array is:

$array = ['Trabalho', 'Jantar', 'Casa', 'Fora'];

You need to pass this to a string so that it stays:

"Trabalho","Jantar","Casa","Fora"

This way you can use IN("Trabalho","Jantar","Casa","Fora") .

  

Considering you are not using bind_param!

For this you have several options that reach the same goal:

You can use implode :

$string = '"' . implode('","', $array) . '"';
// Resultado: "Trabalho","Jantar","Casa","Fora"

If you want you can loop or an array_map maybe.

foreach($array as $i => $coisa){

   $string .= '"';
   $string .= mysqli_real_escape_string($sql, $coisa);
   $string .= '"';
   $string .= $i + 1 < count($array) ? "," : "";

}

Then insert into SQL:

$query = mysqli_query($sql, 'SELECT * FROM Tabela WHERE coisa IN ('.$string.')');

You can add other parameters to WHERE normally.

mysqli_query($link, 'SELECT * FROM tabela where status = "1" AND Data >= "'.$datainicial.'" AND Data <= "'.$datafinal.'" AND coisa IN ('.$string.')'); 

If you prefer to use double quotation marks " you should remove ' :

mysqli_query($link, "SELECT SUM(valor) as valor FROM faturacoes where Status = 1 AND Data >= '$datainicial' AND Data <= '$datafinal' AND posto IN ($postosstring)");

Your current code with ('.$postosstring.') is doing this: '"Trabalho","Jantar","Casa","Fora"' instead of "Trabalho","Jantar","Casa","Fora" .

    
15.01.2017 / 22:30