I have customer table in MySQL database.I have list of customers in excel csv and i want to import excel data into MySQL customer table.I want someone show me step by step How i can do it and also tell model view and controller.
I have Written MySQL Query of customer table to show you that I will be same coloumns in excel csv.
(`CustomerID`, `FirstName`, `LastName`, `JobTitle`, `BusinessPhone`, `MobilePhone`, `FaxNumber`, `Address`, `Area`, `State`, `ZipCode`, `Country`, `Email`, `Webpage`, `Notes`, `CustomerInvoice`, `Status`)
Would you like to show me How i can import csv data into MySQL table or Yii have any plugin to import excel data into MySQL database?
If i understood correctly,you can do something in controller action
public function actionYourActionName(){
if (isset($_FILES['csv_file']) && !empty($_FILES['csv_file'])) {
$csv = array();
$file = fopen($_FILES['csv_file']['tmp_name'], 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
$csv[] = $line;
}
fclose($file);
for ($i = 1; $i < count($csv); $i++) {
$model = new YourmodelName();
foreach ($csv[0] as $key => $value) {
$model->$value = $csv[$i][$key];
}
if($model->save()){
//do here what you want to do after saving model
}else{return $model->getErrors();}
}
}
}else{
$this->render('your view name');
}
and in your view file something like e.g.
echo CHtml::form('', 'post', array('id' => "verticalForm", 'class' => 'well form-vertical', 'enctype' => 'multipart/form-data'));
echo CHtml::fileField('csv_file[]', '', array('id' => 'csv_file', 'multiple' => 'multiple'));
echo '<p class="help-block">Please upload .csv files only.</p>';
echo CHtml::submitButton('Submit', array('class' => 'btn btn-primary'));
echo CHtml::endForm();
and i suppose you have created a model.for your mysql table, hope this will help you
This is best plugin with proper documentation and examples
http://phpexcel.codeplex.com/
with this plugin you can import excel data in mysql.
You can use "LOAD DATA" command.
Here is the example from yiiframework documentation.
http://www.yiiframework.com/wiki/336/importing-csv-file-to-mysql-table-using-load-data-command/
You can get reference from YII: http://www.yiiframework.com/forum/index.php/topic/23536-upload-data-excel-to-mysql/
**step1:**Define a Form model ie
class UserImportForm extends CFormModel
{
public $file;
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('file', 'file',
'types'=>'csv',
'maxSize'=>1024 * 1024 * 10, // 10MB
'tooLarge'=>'The file was larger than 10MB. Please upload a smaller file.',
'allowEmpty' => false
),
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'file' => 'Select file',
);
}
}
step2: Now you need to define a form in your view.ie
Note: i have used bootstrap form widget here.you can change it based on your needs.
<div class="form">
<?php
$form = $this->beginWidget('bootstrap.widgets.BootActiveForm', array(
'id'=>'service-form',
'enableAjaxValidation'=>false,
'method'=>'post',
'type'=>'horizontal',
'htmlOptions'=>array(
'enctype'=>'multipart/form-data'
)
)); ?>
<fieldset>
<legend>
<p class="note">Fields with <span class="required">*</span> are required.</p>
</legend>
<?php echo $form->errorSummary($model, 'Opps!!!', null, array('class'=>'alert alert-error span12')); ?>
<div class="control-group">
<div class="span4">
<div class="control-group <?php if ($model->hasErrors('postcode')) echo "error"; ?>">
<?php echo $form->labelEx($model,'file'); ?>
<?php echo $form->fileField($model,'file'); ?>
<?php echo $form->error($model,'file'); ?>
</div>
</div>
</div>
<div class="form-actions">
<?php $this->widget('bootstrap.widgets.BootButton', array('buttonType'=>'submit', 'type'=>'primary', 'icon'=>'ok white', 'label'=>'UPLOAD')); ?>
<?php $this->widget('bootstrap.widgets.BootButton', array('buttonType'=>'reset', 'icon'=>'remove', 'label'=>'Reset')); ?>
</div>
</fieldset>
<?php $this->endWidget(); ?>
</div><!-- form -->
**step3:**Now you need to write an action in your controller to import the file.ie
public function actionImportCSV()
{
$model=new UserImportForm;
if(isset($_POST['UserImportForm']))
{
$model->attributes=$_POST['UserImportForm'];
if($model->validate())
{
$csvFile=CUploadedFile::getInstance($model,'file');
$tempLoc=$csvFile->getTempName();
$sql="LOAD DATA LOCAL INFILE '".$tempLoc."'
INTO TABLE `tbl_user`
FIELDS
TERMINATED BY ','
ENCLOSED BY '\"'
LINES
TERMINATED BY '\n'
IGNORE 1 LINES
(`name`, `age`, `location`)
";
$connection=Yii::app()->db;
$transaction=$connection->beginTransaction();
try
{
$connection->createCommand($sql)->execute();
$transaction->commit();
}
catch(Exception $e) // an exception is raised if a query fails
{
print_r($e);
exit;
$transaction->rollBack();
}
$this->redirect(array("user/index"));
}
}
$this->render("importcsv",array('model'=>$model));
}
Related
I have a basic form in PHP framework Yii, the action to create works fine, however, when i update the record (for example if i'm not changing the file upload, but another field), it overwrites the file upload and blanks it, can anyone assist me? I've tried all the validation I can think of around the controller items, but no matter what i add it still blanks it on update.
Here's the view code
<?php $form=$this->beginWidget('booster.widgets.TbActiveForm', array(
'id'=>'company-form',
'enableAjaxValidation'=>false,
'method' => 'post',
'type' => 'horizontal',
'htmlOptions' => array(
'enctype' => 'multipart/form-data'
)
));
echo $form->textFieldGroup($model,'name',array('class'=>'col-md-5','maxlength'=>75));
echo $form->fileFieldGroup($model, 'logo',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-md-9',
),
'hint' => 'You can only upload jpg, png, gif\'s – max upload filesize is 1.5mb. Square images are advised.<br/>In certain browsers, you can also drag \' drop files into the dropzone.',
)
);
if($model->isNewRecord!='1'){ ?>
<div class="row">
<label class="col-md-3 control-label" style="padding-top: 25px;">Company image</label>
<div class="col-md-6">
<?php echo CHtml::image(Yii::app()->request->baseUrl.'/images/portraits/company/'.$model->logo,"logo",array("class"=>"img-polaroid placeholder")); ?>
</div>
</div>
<?php } ?>
And this is my actionUpdate function in Controller
public function actionUpdate($id)
{
$model=$this->loadModel($id);
if(isset($_POST['Company']))
{
$model->attributes=$_POST['Company'];
$uploadedFile=CUploadedFile::getInstance($model,'logo');
if (is_object($uploadedFile) && get_class($uploadedFile)==='CUploadedFile'){
if(!$uploadedFile == null){
$rnd = rand(0,9999);
$filename_preg1 = preg_replace("/[^a-zA-Z0-9.]/", '', "{$uploadedFile}");
$fileName = "{$rnd}-{$filename_preg1}";
$company = $model->name;
$model->logo = $fileName;
}
if($model->save()){
if(!empty($uploadedFile)){
$fullPath = Yii::app()->basePath . '/../images/portraits/company/' . $fileName;
$uploadedFile->saveAs($fullPath);
}
$this->redirect(array('view','id'=>$model->company_id));
}
}
if($model->save()){
$this->redirect(array('view','id'=>$model->company_id));
}
}
$this->render('update',array(
'model'=>$model,
));
}
Can anyone see where i'm going wrong?
UPDATE
Thanks SiZE, the code you gave me worked in one form and not in the other, the one it didn't work in has validation in the model rules
array('logo', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'),
This only works with the allowEmpty param here as it's not a required field, however, with the rule in place in the model, it still blanks the file field regardless, anyone have any more thoughts?
CActiveForm calls CHtml::activeFileField method wich generates empty hidden field to correctly work with model's rules.
You can try this:
$model=$this->loadModel($id);
$original_logo = $model->logo;
if(isset($_POST['Company'])) {
$model->attributes = $_POST['Company'];
$logo = CUploadedFile::getInstance($model, 'logo');
$model->logo = $logo !== null ? $logo->getName() : $original_logo;
if ($model->save()) {
if ($logo !== null) {
$logo->saveAs(/* specify path with file name here */);
}
$this->redirect(array('view','id'=>$model->company_id));
}
}
when i upload multiple files in Yii2, i am getting following error and cannot insert data into database:
finfo_file(C:\xampp\tmp\phpCACD.tmp): failed to open stream: No such
file or directory
controller file:
public function actionGallery($id)
{
$model = new Gallery();
if (Yii::$app->request->post()) {
$model->imageFiles = UploadedFile::getInstances($model,'imageFiles');
foreach ($model->imageFiles as $file) {
$imageName = Yii::$app->security->generateRandomString();
$model->added_date = date('Y-m-d');
$model->emp_id = $id;
$file->saveAs('uploads/emp/' . $imageName . '.' . $file->extension);
$originalFile = EMP_PROFILE_ORIGINAL.$imageName.'.'.$file->extension;
$thumbFile = EMP_PROFILE_THUMB.$imageName.'.'.$file->extension;
Image::thumbnail($originalFile, 200, 200)->save($thumbFile, ['quality' => 80]);
$model->save();
}
}
return $this->render('gallery', [
'gal' => $model
]);
}
view file:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\grid\GridView;
?>
<div class="posts-form">
<div class="wrapper-md">
<div class="row">
<div class="col-sm-8">
<div class="panel panel-default">
<div class="panel-body">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($gal, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<div class="form-group">
<button class="btn btn-success">Submit</button>
<a class="btn btn-default" href="<?=\Yii::$app->urlManager->createUrl('post')?>">Cancel</a>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
</div>
</div>
</div>
but i am getting above error. I cannot find the solution for this.
first, in model you must have 2 variable that will save the images and the name of it.
`
* #property string $image_name
*/
class Gallery extends \yii\db\ActiveRecord
{
**public $fileImage=[];**
public static function tableName(){
`
in this case I use $image_name that is one of my model column, and $fileImage, $fileImage is an array that will be used to upload the image,
:)
then in controller
$model = new Gallery(); // this variable is only used to check if everything is valid
if ($model->load(Yii::$app->request->post())) {
$model->fileImage = UploadedFile::getInstances($model,'fileImage');
$a=0;
foreach ($model->fileImage as $file) {
$a++;
$model1 = new Gallery();
$file->saveAs("images/test".$a.".".$file->extension);
$model1->image_url="images/test.".$a.".".$file->extension;
$model1->image_name = "".$a;
$model1->save();
}
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
I think thats all. . .
You can use
$sql = 'INSERT INTO `table`(`id`, `col1`, `col2`, `path`) VALUES (Null,"'.($model2->col1).'","'.($model2->col2).'","'.($model2->path).'")';
$command = \Yii::$app->db->createCommand($sql);
$command->execute();
instead of $model->save();
I made an example,
so the whole code in controller would be:
public function actionCreate()
{
$model = new Planet();
if ($model->load(Yii::$app->request->post()) ) {
$model->file = UploadedFile::getInstances($model, 'file');
foreach ($model->file as $file) {
$model2 = new Planet();
$model2->load(Yii::$app->request->post());
$model2->path='uploads/' . $file;
$sql = 'INSERT INTO `planet`(`id`, `name`, `s_id`, `path`) VALUES (Null,"'.($model2->name).'","'.($model2->s_id).'","'.($model2->path).'")';
$command = \Yii::$app->db->createCommand($sql);
$command->execute();
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
}
return $this->render('view', [
'model' => $model,
]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
It works for me.
edit: also you can use $model2->save(false); It worked in my case.
Call $model->save()
before
$model->file->saveAs();
I was having the exact same problem
*I think you forget to create uploads and emp folder or maybe you use wrong folder name, please check your folder name...
*If you want to save the name of that file, you should use different variable (two variable) that will be used to save the images and the name of that images,
Don't know, if it is a typical problem, but can't figure how to realise it.
3 tables:
Application. It's relations:
return array(
'company_info' => array(self::HAS_ONE, 'AppCompany', 'applicant_id'),
'region'=>array(
self::HAS_ONE,'AppRegion',array('company_region_id'=>'id'),
'through'=>'company_info'
),
'sector'=>array(
self::HAS_ONE,'AppSector',array('company_sector_id'=>'id'),
'through'=>'company_info'
),
);
AppCompany. Relations:
return array(
'application' => array(self::BELONGS_TO, 'Application', 'applicant_id'),
'region' => array(self::BELONGS_TO, 'AppRegion', 'company_region_id'),
'sector' => array(self::BELONGS_TO, 'AppSector', 'company_sector_id'),
'goodsservices' => array(self::HAS_MANY, 'AppGoodsServices', 'company_id')
);
App.GoodsServices. Relations:
return array(
'company'=>array(self::BELONGS_TO, 'AppCompany', 'company_id'),
);
So, one user adds info about his company (company_name, date_of_registration etc), and than add some goods/services that this company produces. How to COLLECT, UPDATE AND VIEW all this information in one form? Is it possible?
How do I see this:
User addes some info and meets the field: "Goods and services and their percentage" and two fields - "GOODS AND SERVICES" and "PERCENTAGE" and ADD MORE button and he has 6 goods that he wants to add. So, he clicks on ADD MORE button and each time the new fields below appear. But the goods limit is 5, so the button becomes inactive after 5 fields have info.
And after SUBMIT button, all this info records to its table. It can be taken from table on UPDATE button and can be viewd in one CDetailView.
Please, how it can be implemented at least in general terms. Thank you
UPDATE
Ok, some work is done (don't know if it right, but...):
I used this extension: http://www.yiiframework.com/extension/esaverelatedbehavior/
Now I have:
public function actionCreate()
{
$model=new Application;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Application']))
{
$model->attributes=$_POST['Application'];
if(isset($_POST['AppGoodsServices']))
{
$model->goodsservices = $_POST['AppGoodsServices'];
}
if ($model->saveWithRelated('goodsservices'))
{
$this->redirect(array('view', 'id' => $model->id));
} else {$model->addError('goodsservices', 'Error occured while saving goods/services.'); }
}
$this->render('create',array(
'model'=>$model,
));
}
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Application']))
{
$model->attributes=$_POST['Application'];
if(isset($_POST['AppGoodsServices']))
{
$model->goodsservices = $_POST['AppGoodsServices'];
}
if ($model->saveWithRelated('goodsservices'))
{
$this->redirect(array('view', 'id' => $model->id));
} else {$model->addError('goodsservices', 'Error occured while saving goods/services.'); }
}
$this->render('update',array(
'model'=>$model,
));
}
public function loadModel($id)
{
$model=Application::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
In my _form.php
<div id="goodsservices">
<?php
$index = 0;
foreach ($model->goodsservices as $id => $goods):
$this->renderPartial('goods/_form', array(
'model' => $goods,
'index' => $id,
));
$index++;
endforeach;
?>
</div>
and subform in goods/_form:
<div style="margin-bottom: 20px; width:100%; clear:left;" class="crow">
<div class="row" style="float: left;">
<?php echo CHtml::activeLabelEx($model, '['.$index.']goods_and_services'); ?>
<?php echo CHtml::activeTextField($model, '['.$index.']goods_and_services', array('size' => 30, 'maxlength' => 150)); ?>
<?php echo CHtml::error($model, '['.$index .']goods_and_services'); ?>
</div>
<div class="row" style="float: left;">
<?php echo CHtml::activeLabelEx($model, '['.$index .']percentage'); ?>
<?php echo CHtml::activeTextField($model, '['.$index.']percentage', array('size' => 5)); ?>
<?php echo CHtml::error($model, '['.$index.']percentage'); ?>
</div>
<div class="row" style="float: left;">
<?php echo CHtml::link('Delete', '#', array('onclick' => 'deleteGoods(this, '.$index.'); return false;'));
?>
</div>
</div>
<div style="clear: both;"></div>
<?php
Yii::app()->clientScript->registerScript('deleteGoods', "
function deleteGoods(elm, index)
{
element=$(elm).parent().parent();
/* animate div */
$(element).animate(
{
opacity: 0.25,
left: '+=50',
height: 'toggle'
}, 500,
function() {
/* remove div */
$(element).remove();
});
}", CClientScript::POS_END);
?>
Everything works, but I cant understand how to make a batch CREATE for children (goodsservices) model. Now it only shows me children in UPDATE form (I've made some records straight into DB) with DELETE button near each. But how to implement CREATE? So, one empty row should be visible and I could ADD other rows on click "Add row"?
It is possible. Using javascript you should create additional items in view, in controller action you are getting $_POST with all data, fill and validate all models in one transaction. In update action view you are showing related models with php foreach.
There is an example of code that can be useful for you. See comments also.
I have a problem with uploading csv file to database. This is my view:
<?php
$this->breadcrumbs = array(
__('People') => array('/contacts'),
__('Persons') => array('admin'),
__('Manage'),
);?>
<h1><?php echo __('People'); ?> <small><?php echo __('import contacts'); ?></small></h1><br/>
<div class="form">
<?php
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'service-form',
'enableAjaxValidation'=>false,
'method'=>'post',
'type'=>'horizontal',
'htmlOptions'=>array(
'enctype'=>'multipart/form-data'
)
)); ?>
<fieldset>
<?php echo $form->errorSummary($model, 'Opps!!!', null, array('class'=>'alert alert-error span12')); ?>
<div class="control-group">
<div class="span4">
<div class="control-group <?php if ($model->hasErrors('postcode')) echo "error"; ?>">
<?php echo $form->labelEx($model,'file'); ?>
<?php echo $form->fileField($model,'file'); ?>
<?php echo $form->error($model,'file'); ?>
</div>
</div>
</div>
<div class="form-actions">
<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'type'=>'primary', 'icon'=>'ok white', 'label'=>'UPLOAD')); ?>
<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'reset', 'icon'=>'remove', 'label'=>'Reset')); ?>
</div>
</fieldset>
<?php $this->endWidget(); ?>
</div><!-- form -->
This is my model:
<?php
class UserImportForm extends CFormModel
{
public $file;
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('file', 'file',
'types'=>'csv',
'maxSize'=>1024 * 1024 * 10, // 10MB
'tooLarge'=>'The file was larger than 10MB. Please upload a smaller file.',
'allowEmpty' => false
),
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'file' => 'Select file',
);
}
}
?>
And this is my function in Controller
public function actionImportCSV()
{
$model=new UserImportForm;
if(isset($_POST['UserImportForm']))
{
$model->attributes=$_POST['UserImportForm'];
if($model->validate())
{
$csvFile=CUploadedFile::getInstance($model,'file');
$tempLoc=$csvFile->getTempName();
$sql="LOAD DATA LOCAL INFILE '".$tempLoc."'
INTO TABLE `contacts`
";
$connection=Yii::app()->db;
$transaction=$connection->beginTransaction();
try
{
$connection->createCommand($sql)->execute();
$transaction->commit();
}
catch(Exception $e) // an exception is raised if a query fails
{
echo "<pre>";
print_r($e);
echo "</pre>";
exit;
$transaction->rollBack();
}
$this->redirect(Yii::app()->createUrl("/contacts/importCSV"));
}
}
$this->render("importcsv",array('model'=>$model));
}
And I have a problem with LOAD DATA, cause mySQL version don't support LOAD DATA. Anyone knows how can I replace load data to import csv file?
Follow the instructions at:
https://github.com/Ardem/yii-importcsv-extension
I followed the simple steps described in readme.md file having the 3 simple steps and it worked like a breeze.
If you are on a version of MySQL tat does not support LOAD DATA, then you are on a very old version indeed. The current online documentation includes LOAD DATA in every mentioned version, though the LOCAL clause is only supported as far back as 3.22.6.
Maybe the real problem is that if you do not specify the FIELDS clause it treats the file as if
FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\'
LINES TERMINATED by '\n' STARTING BY ''
were specified. That is a TAB separated values file in Unix(Linux) text format. To make it comma separated, specify:
LOAD DATA LOCAL INFILE 'data.txt' INTO TABLE tbl_name
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"';
And if you are expecting files from a Windows machine you might want to include
LINES TERMINATED BY '\r\n'
after the FIELDS clause.
I want to select some data in the CodeIgnigher PHP application from the database and want to make some change and insert to another table. I would like to insert as as many as selected records into the IN table. Currently I am getting only one row inserted into the out table.
Can you please point, what is being done wrong here.
My tables are. Out_Table (id, name..) and In_Table (id, name, quantity..).
My Model Code is:
<?php
class ShoppingListM extends CI_Model {
public function getData() {
$query = $this->db->get('products');
return $query->result();
}
function SaveForm($form_data) {
$this->db->insert('SLists', $form_data);
if ($this->db->affected_rows() == '1') {
return TRUE;
}
return FALSE;
}
}
?>
View Code:
<div class="divTable">
<fieldset>
<!-- these will be affected by check all -->
<div class="divRow">Product Name | Quantity | Packages</div>
<div class="divRow"><input type="checkbox" size="100" class="checkall"> Check all</div>
<br>
<?php foreach ($records as $rec) {
?>
<div class="divRow"><input type="checkbox">
<input size="5" type="hidden" value="<? echo $rec->id; ?>" name="id"></input>
<input size="20" type="text" value="<? echo $rec->name; ?>" name="name"></input>
<input size="5" type="text" value="" name="quantity"></input>
<select name="package">
<option name="case">Case</option>
<option name="box">Box</option>
<option name="box">Single Bottle</option>
</select>
</div>
<br>
<?
}
?>
</fieldset>
</div>
<div><input type="submit" name="submit"/></div>
</form>
Controller Code:
class ShoppingListController extends CI_Controller {
public function index() {
//$data['val'] = array("test1", "test2", "test3");
// $this->load->model('HomeModel');
//$data['records'] = $this->HomeModel->getData();
$this->load->model('ShoppingListM');
$data['records'] = $this->ShoppingListM->getData();
$this->form_validation->set_rules('name', 'Name', 'required|max_length[255]');
$this->form_validation->set_rules('qty', 'qty', '');
$this->form_validation->set_rules('package', 'Package', 'required|max_length[128]');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('ShoppingListV', $data);
}
else // passed validation proceed to post success logic
{
// build array for the model
$form_data = array(
'name' => set_value('name'),
'quantity' => set_value('quantity'),
'package' => set_value('package')
);
// run insert model to write data to db
// run insert model to write data to db
if ($this->ShoppingListM->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
{
redirect('ShoppingListController/success'); // or whatever logic needs to occur
}
else
{
echo 'An error occurred saving your information. Please try again later';
// Or whatever error handling is necessary
}
}
well i cannt see where is in_table/out_table in the code u provided yet.
to insert many rows what u want insert_batch
example from doc
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name' ,
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
or u can loop all ur rows from in_table and insert them one by one if its a maintaince job that u dont care about multiple queries
$data= $this->db->get('Out_table');
try
{
if ( $data->num_rows == 0)
throw new Exception('table empty');
foreach( $data->result() as $row)
{
//modifiy the row as u want
$modified=$row;
$q=$this->db->insert('in_table',$modified);
if( ! $q )
throw new Exception('failed to insert row id:'.$row->id);
}
echo $data->num_rows.'rows inserted';
}
catch (Exception $e)
{
echo $e->getMessage();
// Stop method execution with return, or use exit
return;
}