How to print an array of $POST

Hi all

This is probably the easiest question ever :slight_smile: , but I am not familiar with arrays , so hope somebody can help me

User post this checkbox form (array):

<input type=“checkbox” name=“type[0]” value=“1” >
<input type=“checkbox” name=“type[0]” value=“2” >
<input type=“checkbox” name=“type[0]” value=“3” >

I need to get all checked values and print them …
How can I do this?

I tried the code below, but it only returns me one value



$values = array($_POST["type"]);

foreach ($values as $item){

     echo $item;

}


Any help???

Thanks!!

Well, I am trying something like this:


foreach($_POST['type'][0] as $checkbox){
     echo $checkbox; #1, 2 or 3
     $where_str = " AND gu.id_item='".$checkbox."' ";
}


$strSQL = "SELECT DISTINCT id FROM ".PROD_TABLE." gu WHERE gu.active='1' ".$where_str.";     


$rs = $dbconn->Execute($strSQL);

When only one checkbox is checked, I got it working
but when 2 or more are checked, do not find any result.

Any idea?

You would be best off using IN in your WHERE clause. :slight_smile:

This in combination of [fphp]array_map[/fphp], [fphp]intval[/fphp] and [fphp]sprintf[/fphp], you can build a pretty flexible and secure query builder.


<?php
error_reporting(-1);
ini_set('display_errors', true);

$sql = sprintf(
  'SELECT id, name, email FROM table WHERE id IN (&#37;s)',
  implode(
    ',',
    array_map(
      'intval',
      (array)$_POST['type'][0]
    )
  )
);
#SELECT id, name, email FROM table WHERE id IN (1,4,7)
?>

Be sure to read the docs. In brief, we ensure each of the checkboxes is an integer and build the where clause.

Great! it works perfectly.
One last thing: I need to use this in a sql query.
When I place this information into my WHERE condition, I get the last value :frowning:
and i need all values like “AND id=checkbox1 AND id=checkbox2”, etc

How to get them as differents variables? should I use “for” instruction?!



foreach($_POST['type'][0] as $checkbox){
     echo $checkbox; #1, 2 or 3
     $where_str = " AND gu.id_item='".$checkbox."' ";
}


I got it working!!

Thank you!!


<?php
$sql = 'SELECT DISTINCT id FROM ' . PROD_TABLE . ' gu WHERE gu.active = 1';

if(0 < count($_POST['type'][0])){
  $sql .= sprintf(
    ' AND id IN (&#37;s);',
    implode(
      ',',
      array_map(
        'intval',
        (array)$_POST['type'][0]
      )
    )
  );
}

$rs = $db->execute($sql);
?>

Great news, and you’re most welcome. :wink:

This should do it. :slight_smile:


<?php
error_reporting(-1);
ini_set('display_errors', true);

foreach($_POST['type'][0] as $checkbox){
  echo $checkbox; #1, 2 or 3
}
?>