简体   繁体   English

单个html表单以一对多关系插入到多个mysql表中

[英]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: 所以我知道这是一个很普遍的问题,已经有很多答复。但是,我的挑战略有不同,这已经困扰了我好几天了。我有一个html表单,用于将数据存储到我的多个表中数据库(现在使用phpMyAdmin)。这种形式有点不同,该表格允许用户创建调查问题,以及该问题的所有可能答案以及每个问题的首选输入类型,并将它们存储在mysql db中。让我向您展示我的html代码:

 <!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部分:

 <?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: 每个问题可以有多个答案,但只有一种窗口小部件类型。每个答案只能有一个问题,窗口小部件也可以。因此,一个问题_id可能会在答案表中多次出现。

    • 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. 我还要编写一个合适的查询,将question_id插入问题表以及所有相关外键的地方也遇到了挑战。

    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. 坏消息是,您不能在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 插入核心记录时,可以执行另一个sql查询

$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. 如果他们要为现有的附加答案,则需要从某个地方获取question_id,以便上面的脚本起作用。

use mysqli_insert_id() to get the PK genrated for your insert queries 使用mysqli_insert_id()获取为您的插入查询生成的PK
Refer manaual : http://us3.php.net/mysqli_insert_id 请参阅手册: 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.... 不建议使用last_insert_id()因为在同时插入的情况下它无法提供正确的ID。...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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