robins robins - 4 months ago 34
MySQL Question

Insert multiple rows using for loop

I want to insert multiple rows into a table using for loop.But having some errors.
whats wrong in that

$sql=mysql_query("INSERT INTO pl_tbl (p_id,po_name,po_val) VALUES

for ($i=0;$i<$count;$i++)
{
('$id','$data['data']['name_'.$i]','$data['data']['val_'.$i]')");
}


Please help me

Answer

Codeigniter active record has a function insert_batch i think that is what you need

$data = array(
array(
  'p_id' => 'My id' ,
  'po_name' => 'My Name' ,
  'po_val' => 'My val'
),
array(
  'title' => 'Another title' ,
  'name' => 'Another Name' ,
  'date' => 'Another date'
)
);

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

Other way

for ($i=0;$i<$count;$i++) 
  {
     $data = array(
      array(
      'p_id' => $id ,
      'po_name' => $data['data']['name_'.$i] ,
      'po_val' => $data['data']['val_'.$i]
     );
     $this->db->insert('pl_tbl', $data); 
  }