views:

56

answers:

2

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

A: 

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)

littlegreen
the form fields are generated dynamically. Thats why I need a loop.
RisingSun
A: 
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.

Gazler
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.
RisingSun
Gazler
RisingSun
It works but I dont understand it. In what sequence is the array deconstructed
RisingSun