How to solve this codeigniter issue : i have a database table(Mysql) and i need to move all of it\'s field contents to another table using Php Codeigniter framework ?
Wh
A simple one would be
INSERT INTO table1 (col1, col2, col3)
SELECT col1, col2, col3
FROM table2
In CI use query()
$this->db->query("INSERT INTO table1 (col1, col2, col3)
SELECT col1, col2, col3
FROM table2");
Here is the other way
$data = $this->db->select('col1, col2, col3')->get('table2');
if($data->num_rows())
{
$insert = $this->db->insert('table1', $data->result_array());
}
First, get content of first table tableFrom
and iterate over results to insert them to tableTo
. You can use this code in your model. Don't forget $this->load->database();
in your controller or in function.
function insert_into() {
$q = $this->db->get('tableFrom')->result(); // get first table
foreach($q as $r) { // loop over results
$this->db->insert('tableTo', $r); // insert each row to another table
}
}
@EDIT
Try this code for your controller:
<?php
class fdm extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library(array('table','form_validation'));
$this->load->helper('url'); // load model
$this->load->model('cbc','',TRUE);
}
function index() {
$this->load->database();
$this->load->model('cbc','',TRUE);
$this->cbc->insert_into();
}
}
To fix error with duplicate entry for key 1 you might want to truncate first table before you import content from table two. You can do this with:
function insert_into() {
$this->db->truncate('tableTo');
$q = $this->db->get('tableFrom')->result(); // get first table
foreach($q as $r) { // loop over results
$this->db->insert('tableTo', $r); // insert each row to another table
}
}
Or you could update rows instead of inserting new:
function insert_into() {
$q = $this->db->get('tableFrom')->result(); // get first table
foreach($q as $r) { // loop over results
$this->db->update('tableTo', $r, array('id' => $r->id)); // insert each row to another table
}
}