Programmers learn & share
41 views

Solution:

STEP 1: Create a HTML Page with multiple checkboxes

<div class="container">
        <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
            <input type="checkbox" id="Country" name="Country[]" value="India">India<br/>
            <input type="checkbox" id="Country" name="Country[]" value="USA">USA<br/>
            <input type="checkbox" id="Country" name="Country[]" value="Australia">Australia<br/>
            <input type="checkbox" id="Country" name="Country[]" value="Europe">Europe<br/>
            <input type="checkbox" id="Country" name="Country[]" value="Italy">Italy<br/>
            
            <br/><br/>
            <input type="submit" id="submit" name="submit" value="Submit Values" class="btn btn-primary">
        </form>
    </div> <!-- /container -->

 

STEP 2: PHP Code for saving the checkbox values

<?php
    if(isset($_POST["submit"])){
        $countryarr=$_POST["Country"];
        $newvalues=  implode(",", $countryarr);
        include_once './checkboxClass.php';
        $checkBoxClass=new checkboxClass();
        echo $checkBoxClass->addtoDatabase($newvalues);
    }
?>

 

STEP 3: Using class and addtoDatabase() function

public function addtoDatabase($value){
        $insert="Insert into checkbox (Cvalues) values ('$value')";
        $result=$this->query($insert) or die($this->error);
        if($result){
            return "<h2 class='text-success'>Updated</h2>";
        }
        else
        {
            return "<h2 class='text-danger'>Not updated</h2>";
        }
    }

 

STEP 4: Listing saved checkboxes 

<?php
        include_once './checkboxClass.php';
        $checkBoxClass=new checkboxClass();
        $list=$checkBoxClass->listCheckbox("");
?>

<div class="container">
        <table class="table table-bordered table-responsive">
            <thead>
                <tr>
                    <th>Values</th><th>Action</th>
                </tr>
            </thead>
            <?php
            if(count($list)){
                foreach ($list as $value) {
                    echo "<tr><td>$value[Cvalues]</td><td><a class='btn btn-primary btn-sm' href='edit-checkbox.php?id=$value[Id]'>Edit</a></td></tr>";
                }
            }
            ?>
        </table>
    </div> <!-- /container -->

 

STEP 5: Using another function from the checkbox class

public function listCheckbox($query){
        $list="select * from checkbox $query";
        $result=  $this->query($list);
        $count=  $result->num_rows;
        if($count < 1){}else{
            while($row= $result->fetch_array(MYSQLI_BOTH)){
                $arr[]= $row;
            }
            return $arr;
        }
    }

 

posted May 19 in php by (10,020 points)   | 41 views
2,220 questions
2,690 answers
59 comments
241 users