简体   繁体   中英

Php form checked when the checkbox value in array mysql query?

I have and value in my database. It's call type

I have 2 checkbox in my html form.

<input name="barea[]" type="checkbox" id="barea[]" value="1" {$cbvar}/>Normal 
<input name="barea[]" type="checkbox" value="2" id="barea[]" {$cbvar}/>Gold

And I store data as code below:

$checkboxvar = implode(',', $_GET['barea']);

So my table data like:

+-------+-----------+
| ID    | type      |
+-------+-----------+
| 1     | 1         |
| 2     | 1,2       |
| 3     | 2         |
| 4     | 1,2       |
| 5     | 1,2       |
| 6     | 1         |
+-------------------+

When user edit this data, how to checked the checkbox when the barea[] value exist in_array in the mysql_query ?

I try the below coding, in my php file:

$checkbox = explode(',',$row['type']);
if (in_array($_GET['barea'],$checkbox)){
    $cbvar = "checked=\"checked\"";
}else{
    $cbvar = '';
}

In my html

<input name="barea[]" type="checkbox" id="barea[]" value="1" {$cbvar}/>Normal 
<input name="barea[]" type="checkbox" value="2" id="barea[]" {$cbvar}/>Gold

But it can't work, i think maybe the problem is on if (in_array($_GET['barea'],$checkbox)){ .

so how to improve my coding, or any other good coding suggestion? thank you.

=>Try this Code I hope it's useful.

// html page..

<label>Select State</label><br>
<?php 
$allgroup = mysql_query("SELECT * FROM  state");
$flag=false;
while($state_list = mysql_fetch_array($allgroup))
{
   $parr=explode(',',$er['state_id']);
   $size = sizeof($parr);
   for($i=0;$i<$size;$i++) { 
     if($parr[$i]==$state_list['id']) {                              
        $flag=true;
     } 
   }    

  if($flag==true) {
    ?>
    <input  type='checkbox' name='state[]' style="margin-left:5px;" value="<?php echo $state_list['id']; ?>" checked  > <?php echo $state_list['name']; ?> <br>
    <?php
    $flag=false;
  } else { 
    ?>
    <input  type='checkbox' name='state[]' style="margin-left:5px;" value="<?php echo $state_list['id']; ?>"     > <?php echo $state_list['name']; ?> <br>
    <?php
    }
}
?>

// php code ..

<?php
$states="";
$i=0;
foreach( $_POST['state'] as $selected) {
   echo sizeof($_POST['state']);
   if($i==sizeof($_POST['state'])-1) {
       $states = $states.$selected;
   } else {
     $states = $states.$selected.",";
   }
   $i++;
}
?>

Don't forget to sanitize $_POST , it is good coding practice to not access the POST superglobal directly.

+1 for initializing your variables before using them :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM