codeigniter数据库移动到另一个表 [英] codeigniter database moving to another table
问题描述
如何解决这个codeigniter问题:我有一个数据库表(Mysql),我需要将其所有的字段内容移动到另一个表使用Php Codeigniter框架?
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?
我试过玩这些CodeIgniter活动记录查询,但仍然没有运气:这但不工作
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');
}
推荐答案
table tableFrom
并迭代结果以将它们插入到 tableTo
。您可以在模型中使用此代码。不要忘记您的控制器或函数中的 $ this-> load-> database();
。
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
}
}
这篇关于codeigniter数据库移动到另一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!