Someone Someone - 1 year ago 85
MySQL Question

Execut SQL query in codeigniter

I need to execute my SQL query to duplicate MYSQL rows in codeigniter script.

This is my code

if ($para1 == 'duplicate'){
$query = $this->db->query("CREATE TEMPORARY TABLE tmptable_1 SELECT * FROM product WHERE `product_id` = ".$para2);
$query = $this->db->query("UPDATE tmptable_1 SET primarykey = NULL");
$query = $this->db->query("INSERT INTO product SELECT * FROM tmptable_1");
$query = $this->db->query("DROP TEMPORARY TABLE IF EXISTS tmptable_1");

but this dosen't work .

Answer Source

You can use this :

if ($para1 == 'duplicate'){
$table = 'product';
$primary_key_field = 'product_id';
$primary_key_val = $para2;
   /* generate the select query */
   $this->db->where($primary_key_field, $primary_key_val); 
   $query = $this->db->get($table);

    foreach ($query->result() as $row){   
       foreach($row as $key=>$val){        
          if($key != $primary_key_field){ 
          /* $this->db->set can be used instead of passing a data array directly to the insert or update functions */
          $this->db->set($key, $val);               

    /* insert the new record into table*/
    return $this->db->insert($table); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download