I want to insert multiple rows into a table using for loop, but having some errors. What is wrong in this code?
$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]')");
}
Try it:
$sql = "INSERT INTO pl_tbl (p_id,po_name,po_val) VALUES";
$values = [];
for ($i=0;$i<$count;$i++)
{
$values[] = "('$id','$data['data']['name_$i]','$data['data']['val_$i]')";
}
$sql .= join(',', $values);
$result = mysql_query($sql);
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);
}
$data=array();
for ($i=0;$i<$count;$i++)
{
$temp=array();
$temp['p_id'] = 'My id'; //actual value
$temp['po_name'] = 'My Name'; //actual value
$temp['po_val'] = 'My val'; //actual value
array_push($data,$temp);
}
$this->db->insert_batch('pl_tbl', $data);
You can try with this code.
try this simple code its should work for you..
<?php
for($i=0;$i<$count;$i++)
{
$sql="INSERT INTO pl_tbl (p_id,po_name,po_val) VALUES ('$id','$data['data']['name_'.$i]','$data['data']['val_'.$i]')";
$result = mysql_query($sql);
}
?>
thanks
try to save the whole query in a variable and then run with the mysql_query should help you.
so code will be
$sql_query="INSERT INTO pl_tbl (p_id,po_name,po_val) VALUES ";
for ($i=0;$i<$count;$i++)
{
$sql_query.="('$id','".$data["data"]["name_".$i]."','".$data["data"]["val_".$i]."') ";
}
$sql=mysql_query($sql_query);
If I understood this correctly, you should be doing this
for ($i=0;$i<$count;$i++) {
$sql=mysql_query("INSERT INTO pl_tbl (p_id,po_name,po_val) VALUES ('$id','".$data['data']['name_'.$i]."','".$data['data']['val_'.$i]."')");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.