2

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.

2
  • show your mysql table structure Commented Feb 3, 2017 at 10:46
  • i have edit my question, thanks Commented Feb 3, 2017 at 12:36

1 Answer 1

4

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.