-2

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 ?

What is the syntax for inserting data from one table to another table that can be use in my model & controller?

I tried playing with these CodeIgniter Active Record queries but still no luck:this but it doesn't work

function insert_into()  
{    
$this->db->insert('table1');
$this->db->set('to_column');  
$this->db->select('from_column');
$this->db->from('table2');
}
4

2 回答 2

1

一个简单的就是

INSERT INTO table1 (col1, col2, col3)
SELECT col1, col2, col3
FROM   table2

在 CI 中使用query()

$this->db->query("INSERT INTO table1 (col1, col2, col3)
    SELECT col1, col2, col3
    FROM   table2");

这是另一种方式

$data = $this->db->select('col1, col2, col3')->get('table2');
if($data->num_rows())
{
    $insert = $this->db->insert('table1', $data->result_array());
}
于 2013-11-10T20:07:11.100 回答
1

首先,获取第一个表的内容tableFrom并遍历结果以将它们插入到tableTo. 您可以在模型中使用此代码。不要忘记$this->load->database();在您的控制器或功能中。

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
    }
}

@编辑

为您的控制器尝试以下代码:

<?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();
    } 
}

要修复键 1 重复条目的错误,您可能希望在从表 2 导入内容之前截断第一个表。你可以这样做:

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
    }
}

或者您可以更新行而不是插入新行:

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
        }
    }
于 2013-11-10T20:09:20.943 回答