Store variable within a While

1

I have a simple question but it's breaking my head:
I have a form where there are several checkboxes, the value of the checkbox is an id number, I would like to create something that when the user selects a certain number of checks the system make a query in the bank for each id that the user selected. For example, user has selected 3 checkbox, and they contain id 1, 2 and 3, with these parameters the system searches the database for the name related to each id. id 1: name example 1
id 2: name example 2
id 3: name example 3

I tried with while, for etc ... follow code so far that shows me the selected id:

$ocs_imp = $_POST['check_imprime'];
$total=count($ocs_imp);


$inicio = 0;
$ultimo = $total-1;
$arranjo = range($inicio, $ultimo);


     foreach ( arranjo as $n => $v ) {
        echo " o id ".$v." é: ".$ocs_imp[$v]."<br>";
                              } 

The above code shows me, id0 is 1, id1 is 2, etc ...
now how can I use this to make a query to the bank with that id, and bring the "name" column of this id, making this query proportional to the number of checks selected? Thank you and sorry if you were confused.

    
asked by anonymous 13.01.2015 / 21:41

1 answer

1

You can use something like this:

$ids = $_POST['check_imprime'];

// só pra garantir que não terão strings injetadas aqui
foreach($ids as $k => $v) {
  $ids[$k] = (int)$v;
}

$ids = implode(',', $ids);

$sql = "SELECT nome FROM tabela WHERE id IN ($ids)";

// assumindo que as constantes já estejam declaradas...
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); 

$res = $mysqli->query($sql);

while($row = $res->fetch_assoc()) {
   echo 'ID: ' . $row['nome'] . "\n"
}

I did not test this code but I think you can understand the idea.

    
13.01.2015 / 22:06