简体   繁体   中英

Insert dynamic number of checkboxes into many-to-many relationship database

I have a database with a many-to-many relationship with three tables:

+-----------+       +----------+        +----------+
|doorUser   |       |doorAccess|        | doors    |
+-----------+       +----------+        +----------+
| userID    |       | userID   |        | doorNum  |
| lname     |       | doorNum  |        | doorName |
| fname     |       +----------+        +----------+
| username  |
| accessNum |
+-----------+

The doorAccess table is the intermediate table that connects the doorUser and the doors tables. The thing I want to do is to insert into both the doorUser table as well as the doorAccess table, so that each user can have access to any amount of the doors. I have managed to get my PHP to where I can insert into the doorUser table, but the doorAccess table is proving to be a lot more difficult.

The code below is the snippet from the submits and posts.

if (isset($_POST["submit"])) {
                if( (isset($_POST["fname"]) && $_POST["fname"] !== "") && (isset($_POST["lname"]) && $_POST["lname"] !== "") &&(isset($_POST["username"]) && $_POST["username"] !== "") &&(isset($_POST["accessNum"]) && $_POST["accessNum"] !== "")  ) {

                    $query = "INSERT INTO doorUser ";
                    $query .= "(fname,lname,username,accessNum) ";
                    $query .= "values('".$_POST["fname"]."', '".$_POST["lname"]."', '".$_POST["username"]."', '".$_POST["accessNum"]."')";


                    $query3 = "SELECT doorNum, doorName ";
                    $query3 .= "FROM doors ";

                        $result3 = $mysqli->query($query3);
                            while ($row3 = $result3->fetch_assoc())  {
                                $doorNum = $row3["doorNum"];
                                $doorName = $row3["doorName"];


                            if( (isset($row3["doorName"]) && $row3["doorName"] !== "")){

                                $query3 = "INSERT INTO doorAccess ";
                                $query3 .= "(userID, doorNum) ";
                                $query3 .= "values('".$_POST[LAST_INSERT_ID()]."', '".$_POST["doorNum"]."')"

                                }

                            }                       

And the code below is the snippet from the forms:

echo "<p><form action = 'addUser.php?id={$ID}' method='post'>";

                    echo "<p><input type = 'text' name = 'fname' placeholder = 'First Name' /></p>";
                    echo "<p><input type = 'text' name = 'lname' placeholder = 'Last Name' /></p>";
                    echo "<p><input type = 'text' name = 'username' placeholder  = 'username' /></p>";
                    echo "<p><input type = 'text' name = 'accessNum' placeholder = 'password' /></p>";      


                    $query2 = "SELECT doorNum ";
                    $query2 .= "FROM doors ";

                        $result2 = $mysqli->query($query2);
                        if ($result2 && $result2->num_rows > 0) {
                            while ($row2 = $result2->fetch_assoc())  {
                            $doorNum = $row2["doorNum"];

                        echo "<p><input type = 'checkbox' name = 'doorName' value = '".$row2["doorNum"]."' />   Door $doorNum</p>";


                        }
                    }


                    echo "<p><input type = 'submit' name = 'submit' value = 'Add Person' />";   
                    echo "</form>";

The door table is able to be added to or deleted from in another portion, so I need to be able to dynamically generate however many checkboxes for the doors, but then I also need a way to link which users has access to which doors. The checkboxes generate as they're supposed to, but I am having an issue with inserting the userID and the doors into the intermediate table.

I checked and I am able to insert into the doorUser table with this code, but the issue is somewhere in the doorAccess insert.

Any help would be greatly appreciated!

Part of the beauty of the mysqli API is that it affords the use of parameterised queries, eg:

                    $query = "
                    INSERT INTO doorUser 
                    (fname
                    ,lname
                    ,username
                    ,accessNum) VALUES
                    (:fname
                    ,:lname
                    ,:username
                    ,:accessNum);
                    ";

A couple changes should get this working as you expect:

  1. Update the HTML for the checkboxes to use square brackets in the name. That way when the form is submitted, the server-side code (ie PHP) will be able to treat the data as an array (refer to this answer for more details). So this line:

     echo "<p><input type = 'checkbox' name = 'doorName' value = '".$row2["doorNum"]."' /> Door $doorNum</p>"; 

    Becomes:

     echo "<p><input type = 'checkbox' name='selectedDoorNums[]' value = '".$row2["doorNum"]."' /> Door $doorNum</p>"; 
  2. In the PHP code, after inserting into the doorUser table, do a subsequent query to get the newly inserted userID value using the MySQL function LAST_INSERTED_ID() and the PHP-Mysqli method fetch_assoc() .

     $insertDoorUserQuery = "INSERT INTO doorUser "; $insertDoorUserQuery .= "(fname,lname,username,accessNum) "; $insertDoorUserQuery .= "values('".$_POST["fname"]."', '".$_POST["lname"]."', '".$_POST["username"]."', '".$_POST["accessNum"]."')"; $mysqli->query($query); //get inserted Id $lastInsertIdQuery = 'SELECT LAST_INSERT_ID()'; $lastInsertIdResults = $mysqli->fetch_assoc($lastInsertIdQuery); if (count($lastInsertIdResults) && array_key_exists('LAST_INSERT_ID()', $lastInsertIdResults) { $newUserID = $lastInsertIdResults['LAST_INSERT_ID()']; } 
  3. Using the array formed from the changes in Step 1, insert records into the doorAccess table. array_map() can be used to get the list of values to insert, which can be joined using the function implode() .

     if( (isset($_POST["selectedDoorNums"]) && count($_POST["selectedDoorNums"])){ $insertValues = array_map(function($doorNum) use ($newUserID) { return '(' . $newUserID . ', ' . $doorNum . ')'; }, $_POST["selectedDoorNums"]); $query3 = "INSERT INTO doorAccess "; $query3 .= "(userID, doorNum) VALUES ".implode(', ', $insertValues); $mysqli->query($query3); } 

    That way the query stored in $query3 will be of a format similar to

      INSERT INTO doorAccess (userID, doorNum) VALUES(42, 3), (42,6), (42,9) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM