PHP mysql 将关联数组从“动态”数组插入数据库中形式
我有一个允许重复字段的表单。该表单通过 php 发布并插入到数据库中。我的问题是我似乎无法正确循环数组。我是否正确设置了表单(name
的格式是否正确)以及是否正确循环数组?我没有成功插入任何数据。
诀窍在于重复的字段需要粘在一起。
将字段视为问题和答案的集合。
每个问题都有标题、问题文本和文件输入。
每个答案都有一个标题、文件输入的答案文本以及一个用于记录正确答案的复选框。
我的 name
设置如下:
name='question[1][title]'
name='question[1][text]'
name='question[1][file]'
answer[1][title][]
answer[1][text][]
answer[1][file][]
answer[1][correct][]
插入表单的 php 如下:
$insert_question = $db->prepare(
'insert into questions (title, text) values (?, ?)');
$insert_answer = $db->prepare(
'insert into answers (question_id, title, text, correct)'.
' values (?, ?, ?, ?)');
foreach ($_POST['question'] as $q_num => $q)
{
$insert_question->execute(array($q['title'], $q['text']));
$q_id = $db->lastInsertId();
//********************
// insert files
//********************
foreach ($_POST['answer'][$q_num] as $a)
{
$insert_answer->execute(
array($q_id, $a['title'], $a['text'], $a['correct']));
}
}
抱歉,这是一个很大的问题。我已经为此工作了两天,但已经没有想法了。
I have a form that allows for the duplication of fields. The form is posted via php and inserted into a database. My problem is I cannot seem to loop through the array correctly. Am I setting up the form correctly (are the name
's formatted correctly) and am I looping through the arrays correctly? I am not successful in getting any data inserted.
The trick is that the duplicated fields need to stick together.
Think of the fields as sets of questions and answers.
Each question has a title, the question text and a file input.
Each answer has a title, the answer text a file input, and a check box to note the correct answer.
I have the name
's set up like so:
name='question[1][title]'
name='question[1][text]'
name='question[1][file]'
answer[1][title][]
answer[1][text][]
answer[1][file][]
answer[1][correct][]
The php to insert the form is as follows:
$insert_question = $db->prepare(
'insert into questions (title, text) values (?, ?)');
$insert_answer = $db->prepare(
'insert into answers (question_id, title, text, correct)'.
' values (?, ?, ?, ?)');
foreach ($_POST['question'] as $q_num => $q)
{
$insert_question->execute(array($q['title'], $q['text']));
$q_id = $db->lastInsertId();
//********************
// insert files
//********************
foreach ($_POST['answer'][$q_num] as $a)
{
$insert_answer->execute(
array($q_id, $a['title'], $a['text'], $a['correct']));
}
}
Sorry that this is such a huge question. I have been working on this for two days now and have run out of ideas.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定我是否理解你的问题(我英语说得不太流利)。
但这里你需要另一个循环而不是这个循环:
比如:
它没有测试任何东西,只有当你总是得到标题、文本和正确的答案时它才应该工作。
I'm not sure I understood your problem (I don't speak english fluently).
But here you need an other loop instead of this one:
like :
It didn't test anything and it should work only if you always get title, text and correct in an answer.
问题在于第二个循环(答案数组)。试试这个
The issue is with the second loop (answer array). Try this