moonPride
moonPride

Reputation: 141

how to insert json to mysql database with codeigniter

I have html table with value like this : enter image description here

i have convert the value on table to JSON object with jquery plugin tabletoJSON like this :

   [{

    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"

   }]

I want when i click checkout button, it will insert the json data into mysql with codeigniter, how i write the code on my model and controller?

here my table structure :

id_buku : int
jumlah : double
subtotal :double

big thanks.

Upvotes: 2

Views: 9739

Answers (1)

Birdie21
Birdie21

Reputation: 66

Send an object with value of your data(as JSON) to your Controller. e.g (with JQuery):

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

Then in your controller, you can get the Data with this CI method:

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

and if the $data is an Array of objects and you want to filter the $data, you can loop the $data then call the save method in your model

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

Consider to use a transaction to store a lot of data at once. This is necessary to avoid things that are not desirable.

your Model's save method should be like this :

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

Upvotes: 4

Related Questions