2017-02-03 48 views
1

插入JSON到MySQL數據庫中,我有HTML表這樣的值:enter image description here如何與笨

我有表值轉換爲JSON對象與jQuery插件tabletoJSON這樣的:

[{ 

    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" 

    }] 

我想當我點擊結帳按鈕時,它會將json數據插入到帶有codeigniter的mysql中,我如何在我的模型和控制器上編寫代碼?

這裏我表結構:

id_buku : int 
jumlah : double 
subtotal :double 

非常感謝。

+0

顯示你的mysql的表結構 – sintakonte

+0

我有我的編輯問題,謝謝 –

回答

3

向您的Controller發送一個包含數據值的對象(如JSON)。例如(使用jQuery):

$.post('your_action_url', {sendData: JSON.stringify(yourData)}, function(res) { 
    console.log(res); 
}, "json"); 

然後在你的控制器,你可以用這個CI方法得到的數據:

$data = json_decode($this->input->post('sendData')); 

,如果$的數據是Array對象的,你想過濾$數據,你可以循環的$數據然後調用模型中的保存方法

$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!"); 
    } 

考慮使用一個交易STOR一次收集大量數據。這是避免不希望的事情所必需的。

模型的保存方法應該是這樣的:

public function save_as_new($data) { 
    $this->db->insert('your_table_name', $data); 
}