简体   繁体   中英

single html form insert into multiple mysql tables with one to many relationship

So i know that this is a popular question and has a lot of responses already.However, my challenge is slightly different which has been bugging me for days now.I have an html form,which is meant to store data into multiple tables in my database.(using phpMyAdmin for now).What is a bit different is,this form allows the user to create survey questions,along with all the possible answers for that question and the preferred input type for each question and store them in mysql db.Let me show you my html code:

 <!DOCTYPE html>


<html>
    <head>
        <title> Create a new Survey </title>
        <script type="text/javascript" src="script.js"></script>
    </head>
        <body style= "background: #D1D0CE">

        <h1 style= "text-align: center; font-family: Garamond; color: brown">      Create a new survey</h1><br />

            <p style="text-align:center"><img src = "logo.png"/></p>               

            <form action="insert.php"  method="post">

            <fieldset class="row1">

            <table id="formTable" class="form" >
                <tbody>
                <p style="font-family:Garamond; color:brown">
                <strong>Form Information</strong>
                </p> 
                <p>(Please enter your form details below.)</p>

                <tr>
                    <td> Form Name  :  </td><br /><br />
                    <td> <input type="text" size="12" maxlength="40"  name="formName"/></td>

                </tr>
                <tr>
                    <td>Date : </td><br />
                    <td> <input type="date" size="12" maxlength="40"  name="formDate"/></td>
                </tr>
                </tbody>

            </table>
            <fieldset class="row2">
            <table id="questionTable" class="form" >

                <p style= "font-family: Garamond; color: brown">
                <strong>Question Details</strong>
                </p> 

                <p> 
                 <input type="button" value="Add Question" onClick="addRow('questionTable')" /> 
                <input type="button" value="Remove Question" onClick="deleteRow('questionTable')" /> 
                </p>

                    <tr>
                        <p>
                        <td><input type="checkbox" name="chk[]"/></td>
                        <td>
                            <label>Question : </label>
                            <input type="text" size = "16" maxlength= "50"  name="description"/>
                        </td>

                        <td>
                            <label>Input Type :</label>
                            <select id="widgetType" name="widgetType" required="required">
                                <option>....</option>
                                <option>radio button</option>
                                <option>check box</option>
                                <option>Edit Text</option>
                                <option>Spinner</option>
                                <option>Rating bar</option>

                            </select>
                        </td>
                        </p>        
                    </tr>       
            </table>

            <fieldset class="row3">
                <table id="answerTable" class="form">

                    <p style= "font-family: Garamond; color: brown">
                <strong>Answer Details</strong>
                    </p> 

                    <p> 
                 <input type="button" value="Add Answer" onClick="addAnswer('answerTable')" /> 
                <input type="button" value="Remove Answer" onClick="deleteAnswer('answerTable')" /> 
                        <p>(Click to add more answer options.)</p>
                    </p>
                <tr>
                    <p>
                        <td> <input type="checkbox" name="chk[]"/></td>
                        <td><label>Answer : </label>  
                            <input type="text" size="12" maxlength="40"  name="answerText"></td>

                        <td>
                            <label>Match to Question :</label>
                            <select id="QuestionNumber" name="question" required="required">
                                <option>....</option>
                                <option>Question 1</option>
                                <option>Question 2</option>
                                <option>Question 3</option>
                                <option>Question 4</option>
                                <option>Question 5</option>
                                <option>Question 6</option>
                                <option>Question 7</option>
                                <option>Question 8</option>
                                <option>Question 9</option>
                                <option>Question 10</option>

                            </select>


                        </td>   
                        </p>
                    </tr>

                </table>



            <fieldset class="row4">
            <input type="submit" name="submit" value="Submit">
            </form>

        </body>



</html>   

And the php part:

 <?php

    if(isset($_POST['submit'])){

        $host = "localhost"; // host of MySQL server
        $user = "root"; // MySQL user
        $pwd = ""; // MySQL user's password
        $db  = "webservice";  // database name

        // Create connection
        $con = mysqli_connect($host, $user, $pwd , $db);

        // Check connection
        if(mysqli_connect_errno($con)) {
            die("Failed to connect to MySQL: " . mysqli_connect_error());
        }

        $sql = "INSERT INTO form (title,date) VALUES ('".$_POST['formName']."','".$_POST['formDate']."')";


        mysqli_query($con , $sql);





        mysqli_close($con) ;
    }   
?> 

So in my db,i have a the following structure :

  1. Form table

     -form_id(PK, AI) -tile -date 
  2. questions table

     -question_id(PK, AI) -description -form_id(FK) references form_id in form table 
  3. answers table

     -answer_id(PK, AI) -answer_text -question_id(FK) references question_id from questions 
  4. widgets (stores the different widgets/input type chosen from form(radio,text area etc).)

     -widget_id(PK,AI) -widget_type -question_id(FK) references question_id from questions 

    Each question can have more than one answer but only one widget type.Each answer can only have one question and so can the widgets.So a single question_id may appear many times in answers table.This is where i get stuck:

    • Creating the form properly to achieve this.The questions and all it's possible answers are sort of dynamic.So you can decide to add questions and input fields for answers as you go.
    • I can dynamically add more questions and more answers,but can't seem to figure out how to link each answer to it's question.
    • I'm also having a challenge writing a proper query that will insert the question_id into the questions table and all the related foreign keys where it's referenced as well.

    I would really appreciate some pointers so i can head in the right direction.Really sorry for the long question.Thank you

There's good news and some bad news.

The bad news is, you can't insert into multiple tables in 100% sql.

The good news is, you can do it in several steps.

When you insert your core record, you can do another sql query

$getid = mysql_query("SELECT last_insert_id()");
$getid = mysql_fetch_array($getid);
$id = $getid[0];

Then you can use the return from this result for all future inserts, eg:

"INSERT into answers (answer_text, question_id) values ('Some text', " . $id . ")"

The catch is it's best to insert all answers to the question at once, and then move on to the next question.

If they are adding extra answers to an existing from, you will need to get the question_id from somewhere so the above script will work.

use mysqli_insert_id() to get the PK genrated for your insert queries
Refer manaual : http://us3.php.net/mysqli_insert_id

last_insert_id() is not a recommended method as it fails to give proper id in case of simultaneous insertions....

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