Skip to content
Advertisement

Duplicate checkbox remove in php

I have two tables named bookings and packages. Checked checkboxes are retrieved from bookings table and are working perfectly. But I also need unchecked check boxes from packages table. The problem is checked checkbox values display again.

Here is the display screenshot

<?php

$get_pro = "select * from booking";
$result = mysqli_query($con, $get_pro);

$book_packages = $row_pro['Book_Packages'];
$book_packages = substr(trim($book_packages) , 0, -1);
$split_pkg = (explode(",", $book_packages));
if (!empty($split_pkg)) {
    foreach ($split_pkg as $book_pkg) {
        $checked = (in_array($book_pkg, $split_pkg)) ? 'checked="checked"' : '';
?>
                        
        <input type="checkbox" name="pkg_list_name[]" value="<?php echo $book_pkg; ?>" size="17" <?php echo $checked; ?>> <?php echo $book_pkg; ?> <br>
<?php
    }
}

$get_pros = "select * from package";
$results = mysqli_query($con, $get_pros);

while ($row_pros = mysqli_fetch_array($results)) {
    $package_name = $row_pros['Pkg_Name'];

    if ($package_name != $split_pkg) {
        echo "<input type='checkbox' data-parsley-required='true' value='$package_name' data-parsley-trigger='click' id='checkbox1' name='pkg_list_name[]'>&nbsp;&nbsp;
            <label>$package_name</label><br> ";
    } else {

    }
}
?>

Advertisement

Answer

You shouldn’t have two loops. You should only create the checkboxes from the package table. When you’re creating those checkboxes, add checked="checked" if the package name is in $split_pkg.

$book_packages = trim($row_pro['Book_Packages']);
$split_pkg = array_map('trim', explode(',', $book_packages));

$get_pros = "select * from package";
$results = mysqli_query($con, $get_pros);

while ($row_pros = mysqli_fetch_array($results)) {
    $package_name = $row_pros['Pkg_Name'];

    $checked = (in_array($package_name, $split_pkg)) ? 'checked="checked"' : '';
    echo "<label><input type='checkbox' data-parsley-required='true' value='$package_name' data-parsley-trigger='click' name='pkg_list_name[]' $checked>&nbsp;&nbsp;
        $package_name</label><br> ";
}

BTW, it’s not a good idea to to put comma-separated values in database columns. You should have a separate row for each booking. Then you would be able to join the two tables easily.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement