Home > database >  PHP / MySQL: Insert multiple data from checkbox and save it to multiple row in a table
PHP / MySQL: Insert multiple data from checkbox and save it to multiple row in a table

Time:09-26

I'm new to PHP Programming and MySQL. Regarding my question, I have 3 checkboxes. I need to select the data and save it to the database. if I choose 2 data, thus need to save the data 1 by 1, which means will insert two row of data. Below is my code example:

index.php

    <!DOCTYPE html>
    <html>
        <body>
            <h1>Show Checkboxes</h1>
            <form action="save.php" method="POST">
                <input type="checkbox" name="club[]" value="Chelsea">
                <label for="Chelsea"> Chelsea</label><br>
                <input type="checkbox" name="club[]" value="Liverpool">
                <label for="Liverpool"> Liverpool</label><br>
                <input type="checkbox" name="club[]" value="Arsenal">
                <label for="Arsenal"> Arsenal</label><br><br>
                <button type="submit">Submit</button>
            </form>
        </body>
    </html>

save.php

    <?php

    include("connect.php");

        $club = implode(',',$_POST['club']);


        $query = "INSERT INTO bpl_club (club_name) VALUES ('$club')";
        $sql = $conn->prepare($query);
        $sql->execute();

        if($sql){

            echo "<script>alert('Record inserted successfully!')</script>";
            echo "<script>window.location = 'index.php'</script>";

        }else{

            echo "<script>alert('Something went wrong. Please try again!')</script>";

        }

    ?>

Can anyone know how to fix it? Thank you so much..

CodePudding user response:

Use foreach function to print your check box one one by from $_POST['club'] array

$ClubArray=array();
$ClubArray=$_POST['club'];
foreach($ClubArray as $ClubName)
{
//your Insert code here with the insert query ie INSERT INTO bpl_club (club_name) VALUES ('$ClubName')
}
  • Related