简体   繁体   中英

Copy data to another table using sql query and model codeigniter

i'm new to Codeigniter,i'm making something like item in cart system,using temporary table and main table.in my case now,i want to copy data from temporary table(cart) into my main table...but i'm using last insert id to get the ID of order number. here is my SQL tables

    Order            Order Detail                   Cart
  ID | DATE      ID | Order_ID | Item_ID         ID | Item_ID
                                                  1 |    1
                                                  2 |    2

and here is my save controller

function save()
 {
   extract($_POST);
   $date = date('Y-m-d')
   $data = array('date' => $date);
   $this->db->insert('order',$data);
   $order_id = $this->db->insert_id();

   //This is the copy process from Table Cart to Table Order Detail
   $row = $this->db->query('SELECT Item_ID from cart')->row();

   foreach($row as $key)
     {
       // I dont know what to loop....
     }

   $data1 = array('order_id' => $id, 'item_id'=> $key->item_id);
   $this->db->insert('order_detail',$data1);
   $this->db->delete('cart');
 }

i already tried to put $data1 inside my loop,but it doesnt work...the data wont print out...and i tried using normal SQL Query

$this->db->query('INSERT INTO order_detail (item_id)
SELECT item_id
FROM cart');

but i need the variable $order_id inside the normal SQL query. is there any way to do it ? Thanks,..

i already solved my code ....here is my own solution....

function save()
{
   extract($_POST);
   $date = date('Y-m-d')
   $data = array('date' => $date);
   $this->db->insert('order',$data);
   $order_id = $this->db->insert_id();

   //This is the copy process from Table Cart to Table Order Detail
   $this->db->query('INSERT INTO order_detail (item_id)
                     SELECT item_id from cart');
   // End Copy Data
   // Then Update null order_id where order_id = 0

   $this->db->query('UPDATE order_detail
                     SET order_id='.$id.'
                     WHERE order_id=0');
   //End Update

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM