Maestro Vladimir
Maestro Vladimir

Reputation: 1196

Explode Checkbox looping php

I want explode data from table "school_minat" into checklist in checbox looping table from "dayaminat".

I already try, but my checklist show only one. whereas my data minat_id in table school_minat 4 data = smk2,smk3,smk1,smk4

<center> 
<?php $sql = "select * from dayaminat";
$rs = mysql_query($sql);
$i = 0;
while($row = mysql_fetch_array($rs)){  // Looping data from Table "dayaminat"
    ?>
    <input name='minat[]' 
    <?php 
    $values = $result['minat_id']; // Data "minat_id" already Selected in Database table "school_minat"
    $array_of_values = explode(",", $values); //Explode Data "Minat"  already Selected in Database  table "school_minat"
    if (in_array($row['minat_id'],$array_of_values)) {
    echo 'checked="checked"';
    } 
    ?> 
    value='<?php echo $row['minat_id']?>'  type='checkbox'>&nbsp; <?php echo $row['minat'] ?> &nbsp;
    <?php 
    $i ++;
}?>
</center>

Help me. Thank's :)

Upvotes: 1

Views: 3886

Answers (2)

Adrian Cid Almaguer
Adrian Cid Almaguer

Reputation: 7791

You must loop in your $array_of_values

<center> 
<?php $sql = "select * from dayaminat";
$rs = mysql_query($sql);

while($row = mysql_fetch_array($rs)){  // Looping data from Table "dayaminat"
    $values = $result['minat_id']; // Data "minat_id" already Selected in Database table "school_minat"
    $array_of_values = explode(",", $values); //Explode Data "Minat"  already Selected in Database  table "school_minat"

    for($i = 0; $i < count($array_of_values); $i++) {
    echo "<input name='minat[]' ";
    if (in_array($row['minat_id'], $array_of_values)) {
    echo 'checked="checked"';
    } 
    ?> 
    value='<?php echo $array_of_values[$i]; ?>'  type='checkbox'>&nbsp; <?php echo $array_of_values[$i]; ?> &nbsp;
    <?php 
  }
}?>
</center>

Upvotes: 2

Ishan Madhusanka
Ishan Madhusanka

Reputation: 791

You are looping only through the database row. As there is just 1 row you get only 1 result.

So try looping through the array! Probably using foreach loop..

<center> 
<?php $sql = "select * from dayaminat";
$rs = mysql_query($sql);
$i = 0;
while($row = mysql_fetch_array($rs)){  // Looping data from Table "dayaminat"

    $values = $result['minat_id']; // Data "Minat" already Selected in Database table "school_minat"
    $array_of_values = explode(",", $values); //Explode Data "Minat"  already Selected in Database  table "school_minat"?>
    foreach ($array_of_values as $arrayItem){

        <input name='minat<?php echo $i;?>' 
        <?php 

        if (in_array($row['minat_id'],$arrayItem)) {
        echo 'checked="checked"';
        } 
        ?> 
        value='<?php echo $arrayItem ?>'  type='checkbox'>&nbsp; <?php echo $arrayItem ?> &nbsp;
        <?php 
        $i ++;
    }
}?>
</center>

Upvotes: 1

Related Questions