Codeigniter importing data using excel file - php

I am trying to import data via excel sheet into database with codeigniter application.I am using phpexcel. However the code is right but i am getting an error which states:
Error Number: 1054
Unknown column 'joker' in 'field list'
INSERT INTO studentsaccount (joker) VALUES ('')
Filename: C:/xampp/htdocs/Nalanda_Library/system/database/DB_driver.php
Line Number: 691
however my code is as follows: for controller
public function studentaccountimport(){
$this->load->model('Department');
$file = $_FILES['upload']['tmp_name'];
//load the excel library
$this->load->library('excel');
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file);
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only.
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
$this->Department->modeluploadation($data_value);
}
}
}
for model:
public function modeluploadation($data){
$this->db->insert('studentsaccount',$data);
}
i am novice in codeigniter here so please help

You need to specify column names in insert query..
try
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
$data['header'] = $header;
$data['values'] = $arr_data;
$this->Department->modeluploadation($data);

Ok the reason for your problem is you need to pass an array of key=>value pairs as the parameter for insert().
I'm not sure why Safins answer has been marked down because he is right. So when you should set modeluploadation as:
public function modeluploadation($data){
$this->db->insert('studentsaccount',array('field_name'=>$data_value));
}

Related

Is there a way to update 12000+ rows from txt file in less then 2mins?

I need to update a table with more then 12000 row using php Codeigniter and a txt file.. reading the file and the foreach loop are fine but when updating line by line it takes like 30 mins, I guess the problem is I'm searching by name because I have no id in the txt file...
Here is my code:
controller:
$fn = fopen($this->upload->data('full_path'),"r");
$update = true;
while(! feof($fn) && $update) {
$pieces = explode("|", fgets($fn));
if(sizeof($pieces) == 9 && is_numeric(trim($pieces[1]))) {
$update = $this->model_products->update3s($pieces);
}
}
fclose($fn);
Model:
public function update3s($product) {
if ($product) {
$product[2] = trim(str_replace("'","''",$product[2]));
$product[1] = trim($product[1]);
$product[6] = trim($product[6]);
$product[3] = trim($product[3]);
$sql = "UPDATE products set qty = $product[3], price_vente = $product[6] where (name = '$product[2]')";
echo $sql.'<br>';
$update = $query = $this->db->query($sql);
return $update;
}
return false;
}
You can use transaction and add index for column name in database table.
$fn = fopen($this->upload->data('full_path'),"r");
$update = true;
$updatedCount = 0;
while(! feof($fn) && $update) {
$pieces = explode("|", fgets($fn));
if(sizeof($pieces) == 9 && is_numeric(trim($pieces[1]))) {
if ($updatedCount == 0) {
$databaseInstance->beginTransaction();
}
$update = $this->model_products->update3s($pieces);
++$updatedCount;
if ($updatedCount > 500) { //in one transaction update 500 rows
$databaseInstance->commit();
$updatedCount = 0;
}
}
}
if ($updatedCount > 0) { // if we have not commited transaction
$databaseInstance->commit();
}
fclose($fn);
Some tips
Add index to field name
Use prepared statements
Disable the MySQL forgeign key check Read more
writing sql function can do that even in much lesser time .
using feature like :
REPLACE()
cursors
SPLIT_STRING(custom)
in a mysql user defined function
CREATE FUNCTION update3s(hole_file_content LONGTEXT) RETURNS Boolean
BEGIN
-----Your implementation(same logic in sql ) ------
END
then coll it just by if it is CI 3
$this->db->call_function('update3s', file_get_contents($this->upload->data('full_path')));
else
$this->db->query("select update3s(".file_get_contents($this->upload->data('full_path')).")");

Getting Message: Invalid argument supplied for foreach() when there is no records in the table

I have two tables with records. In the first table, I am displaying personal information and in the second table, I am adding the activities details.
Now I am trying to display the record using joins. So below code, I am using in the model
public function getMemberActivity($gotMemberId){
$getDetails = array('members.member_id'=>$gotMemberId,'member_activity.activity_status'=>1,'members.is_Approved'=>1);
$result = $this->db->where($getDetails)
->from('members')
->join('member_activity', 'members.member_id = member_activity.member_id','LEFT')
->get()
->result();
//echo $this->db->last_query();
//print_r($result);
if($result)
{
return $result;
}
else
{
return 0;
}
}
Controller
Note: I am getting multiple member id here because I have above some more logic. that's the reason I am using for each.
$ActivityData=[];
foreach ($data['getAllMember'] as $key => $m_id) {
$ActivityData[] = $this->Access_model->getMemberActivity($m_id->member_id);
}
$data['MemberActivity'] = $ActivityData;
Now If I found the records related the member id in the secondary table then I am getting the output but if not found a record in the second table then I am getting the error Message: Invalid argument supplied for foreach()
If I remove 'member_activity.activity_status'=>1 from the where clause then my join query is working. I mean I am getting the member records.
->join('member_activity', 'members.member_id = member_activity.member_id','LEFT')
View
$SActivity=$MemberActivity;
//print_r($SActivity);
if($SActivity){
foreach ($SActivity as $sec_1) {
foreach ($sec_1 as $sec_activities) {
//list here
}
}
}
else{echo"no data availalbe";}
So my expected output is, I have to display the records if found in the second table if not found then also display the member table records.
Would you help me out in this?
Move your where condition 'member_activity.activity_status'=>1 in JOIN as below,
$public function getMemberActivity($gotMemberId){
$getDetails = array('members.member_id'=>$gotMemberId,'members.is_Approved'=>1);
$result = $this->db->where($getDetails)
->from('members')
->join('member_activity', 'members.member_id = member_activity.member_id AND member_activity.activity_status = 1','LEFT')
->get()
->result();
//echo $this->db->last_query();
//print_r($result);
if($result)
{
return $result;
}
else
{
return 0;
}
}
Hope this will be help you.
Final query like this:
SELECT members.*,member_activity.* FROM members LEFT JOIN member_activity ON members.member_id = member_activity.member_id AND member_activity.activity_status = 1
WHERE 'members.member_id' = $gotMemberId AND 'members.is_Approved' = 1;
The problem is with your model function getMemberActivity. If there is no record then you returns 0 and when you foreach you will get error because its not an array. So you can simply return $result since codeigniter return default array.
public function getMemberActivity($gotMemberId)
{
$getDetails = array('members.member_id' => $gotMemberId, 'members.is_Approved' => 1);
$result = $this->db->where($getDetails)
->from('members')
->join('member_activity', 'members.member_id = member_activity.member_id AND member_activity.activity_status = 1', 'LEFT')
->get()
->result();
return $result;
}
Second option is you can check !empty before your foreach.
I hope this will help you, try
foreach ($SActivity as $sec_1) {
if (!empty($sec_1)):
foreach ($sec_1 as $sec_activities) {
//list here
print_r($sec_activities);
}
endif;
}

codeigniter update data from excel file (Array to string conversion)

I'm try to update data in oracle table from excel file (.xlsx) use CodeIgniter. I've already uploaded the excel file but when I try to update the data I get the following error message:
Message: Array to string conversion
Filename: database/DB_driver.php
Line Number: 1524
Backtrace:
File: C:\xampp\htdocs\web_excel_ci_test\application\models\RoadmapModel.php
Line: 84
Function: update
File: C:\xampp\htdocs\web_excel_ci_test\application\controllers\Roadmap.php
Line: 209
Function: update_data
Controller:
function update(){
$this->load->library('session');
$fileName = $this->session->flashdata('fileName');
$fileName2 = $this->session->flashdata('fileName2');
include APPPATH.'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader->load('excel/'.$fileName);
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true ,true);
$data = [];
$numrow = 1;
foreach($sheet as $row){
if($numrow > 1){
array_push($data, [
'YEAR'=>$row['A'],
'PROVINCEID'=>$row['B'],
'PROVINCE'=>$row['C'],
'PLAN_A'=>$row['D'],
'ACTUAL_A'=>$row['E'],
]);
}
$numrow++;
}
$year = $this->input->post('YEAR');
$this->RoadmapModel->update_data($year, $fileName2, $data);
redirect("Roadmap");
}
Model:
function update_data($year, $fileName2, $data){
for ($i=0; $i < count($year) ; $i++) {
$this->db->where('YEAR', $year[$i]);
$this->db->update($fileName2, $data);
}
}
i think your $data is a multidimentional array, try to use
$this->db->update_batch
to process batch update. You can also look here to for more options.

Symfony 2: Import excel file in the dabase (PHPExcel)

I need to upload an excel file and import the content in the database to the related table.
I have already created a script to import it. The script below works properly
$excelObj = $this->get('phpexcel')->createPHPExcelObject($path_file);
$sheet = $excelObj->getActiveSheet()->toArray(null,true,true,true);
$em = $this->getDoctrine()->getManager();
//READ EXCEL FILE CONTENT
foreach($sheet as $i=>$row) {
if($i !== 1) {
$account = $em->getRepository('ExcelBundle:Users')->findOneByUsername($row['A']);
if(!$account) {
$user = new Users();
}
$user->setName($row['A']);
$user->setUsername($row['B']);
$user->setEmail($row['C']);
//... and so on
$em->persist($user);
$em->flush();
}
}
Now, instead of importing the row A, row B...etc of the excel file I need to import the name of the row.
name username email ...and so on
$user->setName($row['name']);
$user->setUsername($row['username']);
$user->setEmail($row['email']);
How can I do it?
So you need to map the headings row (row #1) to the actual values in each subsequent row
foreach($sheet as $i=>$row) {
if($i == 1) {
$headings = $row;
} else {
$row = array_combine($headings, $row);
.... do the rest of your stuff here
$user->setName($row['name']);
$user->setUsername($row['username']);
$user->setEmail($row['email']);
....
}

Retrieving value from database in CodeIgniter is not working

In my Codeigniter project ,table value is not retrieving from database.Am using MySQL (WAMP) as database.Using Select Query i have checked the data in database and its fine there.When updating the same also its retrieving the old value in db.But when retrieving the value in later stage (ie,taking old bill) its not retrieving the value.The problem is happening only on the single field(ie,actual_price).How to solve this error.Here am attaching the screenshot and controller code for the same.
Controller Code
function bill_view($billid)
{
if(!$billid) {
redirect('report/bill_report');
}
$salecode =str_replace("_","/",$billid);
$filter ="gm_sale.saleCode ='$salecode'";
$billArray =$this->sale_model->getBillinfo($filter);
$exshowroom='';
$bank ='';
$scheme='';
$wcoNo ='';
$saleId =0;
foreach($billArray as $key=>$val) {
$exshowroom = $val['actual_price'];
$date =$val['saledate'];
$sale_to=$val['saleCustomer'];
$saleUserId=$val['saleUserId'];
$wcoNo = $val['wcoNo'];
$saleId= $val['saleId'];
if(!is_null($val['bank']) && !empty($val['bank'])){
$bank =$val['bank'];
}
if(!is_null($val['scheme_id']) && !empty($val['scheme_id'])){
$array_scheme = unserialize($val['scheme_id']);
///////////////////////////////////////////
foreach ($array_scheme as $val_scheme_id) {
$res_scheme = $this->db->get_where("gm_scheme",array('id'=>(int)$val_scheme_id));
if($res_scheme->num_rows >0){
$arrscheme = $res_scheme->row_array();
if(!empty($scheme)) {
$scheme .= ",";
}
$scheme .= $arrscheme['schemeName'];
}
}
/////////////////////////////////////////////
}
break;
}
$query = $this->db->get_where('gm_users',array('userId'=>(int)$saleUserId));
if($query->num_rows >0) {
$arrUser =$query->row_array();
}else{
$arrUser =array();
}
$data['list_product'] = $billArray;
$data['exshowroom']=$exshowroom;
$data['userinfo'] =$arrUser;
$data['saleCode'] =$salecode;
$data['sale_to'] =$sale_to;
$data['added_date'] =$date;
$data['bank'] =$bank;
$data['scheme'] =$scheme;
$data['wcoNo'] =$wcoNo;
$data['saleId'] =$saleId;
$this->load->view('header_login');
$this->load->view('report/bill_view',$data);
//print_r($billArray);
$this->load->view('footer_login');
}
Model Code
function getBillinfo($filter=''){
$this->db->select('*,gm_sale.added_date as saledate');
$this->db->from('gm_sale',FALSE);
$this->db->join('gm_products',"gm_sale.productId=gm_products.productId",FALSE);
$this->db->join('gm_model',"gm_products.model_id=gm_model.id",FALSE);
$this->db->join('gm_banks',"gm_sale.bank_id=gm_banks.bank_id","LEFT");
if($filter<>"")
$this->db->where($filter,'',FALSE);
$this->db->order_by('gm_sale.saleId',"desc");
$query = $this->db->get();
print_r($query);
if($query->num_rows>0) {
$arrRow =$query->result_array();
print_r($arrRow);
return($arrRow);
}
return(array());
}
Your code that you have in the controller doing DB stuff should be in the model.
The controller does not have context to
$this->db
modify your joins (3rd param) to retrieve values in actual_price

Categories