Store Variable within a While

Asked

Viewed 604 times

2

I’m having a simple doubt but it’s cracking my head:
I have a form where there are several checkbox, the checkbox value 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 database for each id that the user selected. For example, the user selected 3 checkbox, and they contain id 1, 2 and 3, with these parameters the system searches in the database the name related to each id.
id 1 : example name 1
id 2 : example name 2
id 3 : example name 3

I tried while, for etc... follow code until the moment it 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 query the bank with this id, and bring the "name" column of this id, making this query proportional to the number of checks selected? thanks and sorry if you got confused.

1 answer

1


You can wear something like that:

$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 haven’t tested this code but I think you can understand the idea.

  • It worked André, thank you very much for the strength, simple and perfect, another doubt, really need that part of the foreach? because the value received is not entered by the user, but a checkbox value.

  • 1

    @Denisl.Murara It’s good to ensure that all Ids are int (what’s not turns 0). If removing you will have to escape the ids before or (better) use prepare http://php.net/manual/en/mysqli.prepare.php#refsect1-mysqli.prepare-examples

Browser other questions tagged

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