PHP将多个值插入MySQL表中的单独行

问题描述:

我有一个PHP表单,其中包含各种类型的输入字段(复选框,下拉列表,单选,自动完成等).我想做的就是让用户输入(对于多个输入,可能有多个值).例如,有一个问题:您最喜欢哪部电影?他可能会写多于1部电影),并将这些值存储在Mysql表的不同行中. 这是我数据库中的表:

I have a PHP form with various types of input fields (checkbox, drop-down, radio, auto-complete, etc.) What I would like to do is get users input(which might be more than one value, for instance, for question: which is your favourite movie? he might write more than 1 movie) and store these values in separate rows in Mysql table. here are tables in my database:

答案: ID,用户ID,问题ID,答案

成员:用户ID,姓名,姓氏等.

问题:questionId,questionText

我能做的是这样的:(注意:在这种情况下,设计会有所不同,这里我对每个问题都有一个单独的字段)

What I can do is something like this:(Note: in this case the design would be different, here I have a separate field for each question)

$stmt = $conn->prepare('UPDATE test SET q1 = :q1, q2 = :q2, q3 = :q3, q4 = :q4, q5 = :q5, q6     = :q6, q7 = :q7 WHERE username = :username');
$stmt->execute(array(':q1' => $q1,':q2' => $q2, ':q3' => $q3, ':q4' => $q4, ':q5' => $q5, ':q    6' => $q6, ':q7' => $q7, ':username' => $_SESSION['SESS_USERNAME']));

这种方法的问题是,在同一行中插入了多个值答案,并用逗号分隔(例如,如果用户写了"Tom cruise"和"Brad Pitt",则将这两个名称都存储在同一行中)

My problem with this approach was that multiple value answers were inserted in the same row with a comma separated them(for instance if user wrote "Tom cruise" and "Brad Pitt", it stored both these names in the same row)

我认为我必须用这样的东西代替它:

I thought I have to replace it with something like this:

$stmt = $conn->prepare('INSERT INTO Answer (qId, answer) VALUES (:qId, :answer)');

但是在这里我不知道如何定义qId? (如何识别每个答案与哪个问题有关)

but here I don't know how to define qId? (how it can recognize that each answer is related to which question)

在下面的代码中,我可以从数据库中获取问题并将其存储在数组中,但是我仍然不确定如何完成此代码.对于每个问题,它都插入qId,并且答案用户已经插入...对吗?)

In the code below, I can fetch questions form database and store it in array, but still Iam not sure how to complete this code.. should I write insert statement inside the loop (the loop which get questions from DB, so for each question, it insert qId and the answer user has inserted... am I right ??)

$arr = array(); 
$sql="select qId from question"; 
$result = mysql_query($sql) or die(mysql_error());
while( $row = mysql_fetch_assoc( $result ) ) {
   arr[] = $row[ 'qId' ]; 
} 

有人可以帮助我知道如何将这些值插入多行吗?

Could someone kindly help me to know how I can insert these values into multiple rows?

非常感谢,

问题的ID可以在后端排列.您可以遍历数组并循环插入问题.

The id for the question can be array at the backend side. You can iterate over the array and insert questions in loop.

另一种方法是使用变量变量在for循环中编写变量名称.

在我看来,数组似乎是一个更干净的代码. :)

Array seems like a cleaner code to me. :)