我已经使用 jquery 插件 tabletoJSON 将表上的值转换为 JSON 对象,如下所示:
[{
harga_jual : "47025",
id_buku : "1",
judul_buku : "perempuan dam hak warisnya",
jumlah : "1",
subtotal : "47025"
},
{
harga_jual : "49500",
id_buku : "2",
judul_buku : "Keajaiban Operasi Plastik Korea Selatan",
jumlah : "2",
subtotal : "99000"
}]
我想当我点击结账按钮时,它会使用codeigniter将json数据插入到mysql中,我如何在我的模型和 Controller 上编写代码?
这是我的表结构:
id_buku : int
jumlah : double
subtotal :double
非常感谢。
最佳答案
将包含数据值(JSON 形式)的对象发送到您的 Controller 。例如(使用 JQuery):
$.post('your_action_url', {sendData: JSON.stringify(yourData)}, function(res) {
console.log(res);
}, "json");
然后在您的 Controller 中,您可以使用此 CI 方法获取数据:
$data = json_decode($this->input->post('sendData'));
如果 $data 是一个对象数组并且您想要过滤 $data,您可以循环 $data 然后调用模型中的 save 方法
$this->db->trans_begin();
foreach($data as $row) {
$filter_data = array(
"id_buku" => $row->id_buku,
"jumlah" => $row->jumlah,
"subtotal" => $row->subtotal
);
//Call the save method
$this->your_model_alias->save_as_new($filter_data);
}
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
echo json_encode("Failed to Save Data");
} else {
$this->db->trans_commit();
echo json_encode("Success!");
}
考虑使用事务一次存储大量数据。这是避免出现不良情况所必需的。
你的模型的保存方法应该是这样的:
public function save_as_new($data) {
$this->db->insert('your_table_name', $data);
}
关于mysql - 如何使用codeigniter将json插入mysql数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42014813/