0
votes

I am Inserting a multiple form input data in to database using Codeigniter. I have this post input array:

 Array
(
 [subject_id] => Array
    (
        [0] => 1
        [1] => 1
    )

[question] => Array

    (
        [0] => test
        [1] => test2
    )

[option1] => Array
    (
        [0] => test
        [1] => test2
    ) )

I don't get that how do i convert this array to insert How to insert this array using Insert batch.

$this->db->insert_batch('mytable', $data);

This is the form code which i use for posting the data:

                <form method="post">
            <input type="text" name="subject_id[]" >
            <input type="text" name="question[]" >
            <input type="text" name="record[]" >

            // Down side Part is appended when user want to add more question

            <input type="text" name="subject_id[]" >
            <input type="text" name="question[]" >
            <input type="text" name="record[]" >

            <input type="submit" name="submit" >
            </form>

Below is the Array format which i want.

$data = array(
            array(
                'subject_id' => 'My title' ,
                'question' => 'My Name' ,
                'option1' => 'My date'
                ),
            array(
                'subject_id' => 'Another title' ,
                'question' => 'Another Name' ,
                'option1' => 'Another date'
                )
            );
2
post your code in your question regarding how do you get this array? - dhruv jadia
Sir I Have updated the question. @dhruvjadia - ankit suthar
I have updated the question again sir & added what the result array i need. @dhruvjadia - ankit suthar
provided answer - dhruv jadia

2 Answers

4
votes
<?php
    $i = 0;
    foreach($subject_id as $key=>$val)
    {
          $data[$i]['subject_id'] = $val;
          $data[$i]['question'] = $question[$key];
          $data[$i]['option1'] = $record[$key];
          $i++;
    }
    $this->db->insert_batch('mytable', $data);

?>
2
votes

Try like below:Assume $records is an array that you want to insert.

foreach ($records as $record) 
{

    for ($i=0; $i < count($record); $i++) 
    {   
    $data[$i]['subject_id'] = $record['subject_id'][$i];
    $data[$i]['question'] = $record['question'][$i]
    $data[$i]['option1'] = $record['option1'][$i];
    }

}

Then

$this->db->insert_batch('mytable', $data);