开发者

PHP mysql insert associative array into database from a "dynamic" form

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.


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:

   foreach ($_POST['answer'][$q_num] as $a)
   {
      $insert_answer->execute(
         array($q_id, $a['title'], $a['text'], $a['correct']));
   }

like :

$lim = count($_POST['answer'][$q_num]['title']);
for($i=0;$i<$lim;++$i){
   $insert_answer->execute(
             array($q_id, $_POST['answer'][$q_num]['title'][$i], $_POST['answer'][$q_num]['text'][$i], $_POST['answer'][$q_num]['correct'][$i]));
}

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

<?php 
  foreach ($_POST['answer'][$q_num]['title'] as $a => $value)
   {
    $insert_answer->execute(
       array($q_id, $_POST['answer'][$q_num]['title'][$a], $_POST['answer'][$q_num]['text'][$a], $_POST['answer'][$q_num]['correct'][$a]));
}

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜