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

Community
  • 1
  • 1
Mr Hyde
  • 3,393
  • 8
  • 36
  • 48

2 Answers2

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)

littlegreen
  • 7,290
  • 9
  • 45
  • 51
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.

Gazler
  • 83,029
  • 18
  • 279
  • 245
  • 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. – Mr Hyde Oct 03 '10 at 22:06
  • 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. – Gazler Oct 03 '10 at 22:09
  • Yes, I didnt have to use the '&'. – Mr Hyde Oct 03 '10 at 22:11
  • It works but I dont understand it. In what sequence is the array deconstructed – Mr Hyde Oct 03 '10 at 22:26