我想插入两行,但每行的 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)
在汽车中,我想在两个汽车 ID 217450、217449 上插入价格、createdDate 和 createdBy。
提前谢谢你。
最佳答案
$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 注入(inject)攻击。
因此,请使用 CI 的 事件记录
:
$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
关于php - 在 Codeigniter 中插入 ID 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25154552/