我试图插入两行,但每行的ID都在同一个数组中,如何正确插入?
因为我试过这种方式但只插入第一个id。
$sql = "
INSERT INTO cars(car, price, createdDate, createdBy)
VALUES (".$this->db->escape($ids).",
".$this->db->escape($price).",
NOW(),
".$this->session->userdata('admin_id').")";
mysql_query($sql);
echo ($sql);
这就是我得到的:
INSERT INTO cars (car, price, createdDate, createdBy)
VALUES ('217450,217449', '15', NOW(), 150)
在车里,我想在两辆车216450,217449上插入价格,createdDate和createdBy。
提前谢谢。
答案 0 :(得分:1)
使用PHP函数explode
:
$ids= explode(',', $ids);
foreach($ids as $id)
{
$sql = "INSERT INTO cars(car, price, createdDate, createdBy)
VALUES (" . $this->db->escape($id) . ", " . $this->db->escape($price)
. ", NOW(), " . $this->session->userdata('admin_id') . ")";
mysql_query($sql);
}
答案 1 :(得分:1)
$ids = "217450, 217449";
$id_explode = explode(",", $ids);
foreach($id_explode as $id)
{
$sql = "
INSERT INTO cars(car, price, createdDate, createdBy)
VALUES (".$this->db->escape($id).",
".$this->db->escape($price).",
NOW(),
".$this->session->userdata('admin_id').")
";
mysql_query($sql);
echo ($sql);
}
但我建议您不要使用原始SQL查询,因为容易受到SQL注入。
因此,使用CI' s active record
:
$ids = "217450, 217449";
$id_explode = explode(",", $ids);
$insert_batch = array();
foreach($id_explode as $id)
{
$arr = array(
'car' => $id,
'price' => $price,
'createdDate' => NOW(),
'createdBy' => $this->session->userdata('admin_id'),
);
$insert_batch[] = $arr;
}
$this->db->insert_batch('cars', $insert_batch);
的文档:强>
https://ellislab.com/codeigniter/user-guide/database/active_record.html
答案 2 :(得分:1)
如果你使用id作为数组 $ ids = array('217450','217449');
$sql = "
INSERT INTO cars(car, price, createdDate, createdBy)
VALUES ";
foreach($ids as $id){
$sql .=(".$this->db->escape($id).",
".$this->db->escape($price).",
NOW(),
".$this->session->userdata('admin_id')."),";
}
mysql_query($sql);
echo ($sql);
现在它将创建查询
INSERT INTO cars (car, price, createdDate, createdBy)
VALUES ('217450', '15', NOW(), 150),('217450', '15', NOW(), 150);