0

I asked a question on SO a few hours back.

How to insert an Array of field names from a form into SQL database in Codeigniter.

<tr>
<td><input type="text" name="user[0][name]" value=""></td>
<td><input type="text" name="user[0][address]" value=""><br></td>
<td><input type="text" name="user[0][age]" value=""></td>
<td><input type="text" name="user[0][email]" value=""></td>

<tr>
<td><input type="text" name="user[1][name]" value=""></td>
<td><input type="text" name="user[1][address]" value=""><br></td>
<td><input type="text" name="user[1][age]" value=""></td>
<td><input type="text" name="user[1][email]" value=""></td>
</tr>
..........//so on

This is the best answer I got

foreach($_POST['user'] as $user)
 {
    $this->db->insert('mytable', $user);
 }

Now I want to pass a id generated from user session data into this array + a few other values like current time

Is it possible to tweak the above solution?

The Previous Discussion Here

2 Answers 2

0
foreach($_POST['user'] as &$user)
 {
    $user['additional_data'] = $_SESSION['additional_data'];
    $user['current_time'] = time();
    $this->db->insert('mytable', $user);
 }

Note the & in &$user which is a pass by reference which allows manipulation of an array within a foreach loop. If you reference user later remember to unset($user) to remove the reference to the last element of the $_POST['user'] array.

Sign up to request clarification or add additional context in comments.

4 Comments

Spot on! It seems to be a conspiracy against me. I try all variations which throw all kinds of errors at me, then someone @ SO works it out in a millisecond. :-) Thanks.
Actually, looking at it, you can ignore the pass by reference (& before &$user) and it should still work. Passing by reference is only useful if you use the $_POST['user'] array anywhere else in the code.
Yes, I didnt have to use the '&'.
It works but I dont understand it. In what sequence is the array deconstructed
0

I don't know if I'm missing something here, but can't you just remove the foreach and build your code like this:

$var1 = $_POST['user_var1'] * 3 + 1 / 5;
$this->db->insert('mytable', $var1);
$var2 = gettime();
$this->db->insert('mytable', $var2);
....

(where gettime() should be replace with whatever the PHP command for getting time is, plus maybe a formatting function)

1 Comment

the form fields are generated dynamically. Thats why I need a loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.