[英]Insert multiple rows using for loop
I want to insert multiple rows into a table using for loop, but having some errors. 我想使用for循环在表中插入多行,但是有一些错误。 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: Codeigniter活动记录具有功能insert_batch我认为这是您需要的:
$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. 尝试将整个查询保存在一个变量中,然后与mysql_query一起运行应该会对您有所帮助。
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]."')");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.