codeigniter database moving to another table

前端 未结 2 923
梦谈多话
梦谈多话 2021-01-29 14:06

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

相关标签:
2条回答
  • 2021-01-29 14:15

    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());
    }
    
    0 讨论(0)
  • 2021-01-29 14:32

    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
            }
        }
    
    0 讨论(0)
提交回复
热议问题