Search code examples
phpmysqlwebcheckboxdreamweaver

Inserting multiple rows into MySQL with checkbox


Below is my code. I have two MySQL database tables, one is "member" and another one is "participants". I would like to display the data in table "member" to my local host page and I did it. However, I cannot insert multiple rows of "member" data by using checkbox to my database table "participants". I am stuck. Any help is much appreciated.

<?php
try {
    $con = new PDO("mysql:host=localhost;dbname=kgruum member", "root", "");
    $sql = $con->query("SELECT * FROM member");
    echo "<table class='info' align='center' border='1'>";
    echo "<tr><td width='10'></td>
        <td width='10'><b>ID</b></td>
        <td width='500'><b>Name</b></td>
        <td width='50'><b>Handicap</b></td><tr>";

    foreach($sql as $row) {
        $ID = $row["ID"];
        $Name = $row["Name"];
        $Handicap = $row["Handicap"];
        echo "<tr>
            <td><form method='POST' action='Add participant.php'><input type='checkbox' name='insert[]' value='$ID'></td>
            <td>$ID</td>
            <td>$Name</td>
            <td>$Handicap</td><tr>";
    }

    echo"</table><div align='center'><input type='image' value='submit' src='add selected button.png' alt='submit Button' onmouseover='this.src='pink add selected button.png'' onmouseout='this.src='add selected button.png'' name='add_btn' id='add_btn'></div><br></form>";


    if(isset($_POST['add_btn'])) {
        if(!empty($_POST['insert'])) {
            foreach($_POST['insert'] as $check) {
                $st=$con->prepare("INSERT INTO participants(ID,Name,Handicap) VALUES('$ID','$Name','$Handicap')");
                $insert->bindParam('ID',$ID);
                $insert->bindParam('Name',$Name);
                $insert->bindParam('Handicap',$Handicap);
                $st->execute();
                }
           echo "<script type='text/javascript'>
               alert('Successful Insert ! ');
               window.location.href = 'Add participant.php';
               </script>";
         } else {
           echo "<script type='text/javascript'>alert('You didn't choose which user you want to insert ! ')</script>";
      }
    }
} catch(PDOException $e) {
    echo "error".$e->getMessage();
}
?>

Solution

  • You are not storing the $Name and $Handicap values in the insert[] array, you only storing the $ID value.

    To resolve, do something like this:

    <input type='checkbox' name='insert[]' value='$ID|$Name|$Handicap'>
    

    Then:

    foreach($_POST['insert'] as $check) {
      $values = explode('|', $check);
      $ID = $values[0];
      $Name = $values[1];
      $Handicap = $values[2];
      //The rest of your SQL code goes here as you have it...
      $check = ''; 
    }