Codeigniter update_batch--view, but not execute - codeigniter

I am using Codeigniter 3.x and want to see an update_batch query, but not run it, while I am debugging the code.
This works for an update_batch:
$this->db->update_batch("`" . $this->fullGamesTable . "`", $fullGames, 'gameid');
and updates the database, but I want to view the update and not actually do the update.
Thanks.

Can you do like this
$data = array(
array(
'opt_id' => $hoptid1,
'q_id' => $hid,
'opt_val' => $sin_yes,
'opt_crct' => $sin_yescrt,
'opt_mark' => '1'
),
array(
'opt_id' => $hoptid2,
'q_id' => $hid,
'opt_val' => $sin_no,
'opt_crct' => $sin_nocrt,
'opt_mark' => '1'
)
);
$this->db->update_batch('option', $data, 'opt_id');

Try this
public function update_batch()
{
$data = $this->db->select('id,description')->from('insert_batch')->group_by('url')->get()->result_array();
$batch_update = [];
foreach ($data as $key => $value) {
$value['description'] = 'description';
$batch_update[] = [
'id' =>$value['id'],
'description' => $value['description']
];
}
echo "<pre>"; print_r($batch_update);
$this->db->update_batch('insert_batch',$batch_update,'id');
}

Related

Undefinde offset:1 when importing laravel excel

this my code cause the trouble,
$cust = Customer::where('name', '=', $data[$i][0]['customer_name'])
->pluck('customer_id')[0];
this one for get customer id when i do store to sales order
$sales = array(
'customer_id' => Customer::where('name', '=', $data[$i][0]['customer_name'])->pluck('customer_id')[0],
'logistics_id' => Logistic::where('logistics_name', '=', $data[$i][0]['logistics'])->pluck('logistics_id')[0],
'subtotal' => $data[$i][0]['subtotal_rp'],
'shipping_cost' => $data[$i][0]['shipping_cost_rp'],
'discount_code' => 0,
'date_of_sales' => $data[$i][0]['date'],
'grand_total' => $data[$i][0]['grand_total_rp'],
'tax' => $data[$i][0]['tax_rp'],
'status' => $data[$i][0]['status'],
'discount_amount' => $data[$i][0]['discount_amount_rp']
);
$store_so = SalesOrder::create($sales);
but, when i do dd(), i get the right data
First of all, you need to check if the $data variable returns the data as you expect.
dd($data);
Next, you need to check that the $data array has the number of elements according to $total_data.
dd(count($data) == $total_data));
So basically, you just need to give condition or try-catch (recommended) :
if (isset($data[$i][0])) {
$customer = Customer::where('name', $data[$i][0]['customer_name'])->first();
$logistic = Logistic::where('logistics_name', $data[$i][0]['logistics'])->first();
if(!$customer){
dd('No customer found!');
}
if(!$logistic){
dd('No logistic found!');
}
$sales = [
'customer_id' => $customer->customer_id,
'logistics_id' => $logistic->logistics_id,
'subtotal' => $data[$i][0]['subtotal_rp'],
'shipping_cost' => $data[$i][0]['shipping_cost_rp'],
'discount_code' => 0,
'date_of_sales' => $data[$i][0]['date'],
'grand_total' => $data[$i][0]['grand_total_rp'],
'tax' => $data[$i][0]['tax_rp'],
'status' => $data[$i][0]['status'],
'discount_amount' => $data[$i][0]['discount_amount_rp'],
];
$store_so = SalesOrder::create($sales);
}
else{
dd('No $data[$i][0] found!');
}
PS : I recommend using the first() method instead of pluck('customer_id')[0].
It seems you need to get a customer_id from a customer_name.
Try to make everything simple:
$sales = array(
'customer_id' => Customer::where('name', $data[$i][0]['customer_name'])->first()->id,
...
);

How to add an array within a foreach in laravel controller?

I am trying to insert data from a form which i get it in the form of an array and i am using a foreach to insert the data each in to the database. amongst these data i have another array that i need to insert it in the form of an array.
The Amendities should be saved in the form of an array! i tried using implode but didn't quite get the results i expected.
foreach ($request->room_type as $item => $v) {
$data2 = array(
'room_type' => $request->room_type[$item],
'no_of_pax' => $request->no_of_pax[$item],
'no_of_pax_children' => $request->no_of_pax_children[$item],
'cost_per_adult' => $request->cost_per_adult[$item],
'cost_per_child' => $request->cost_per_child[$item],
'room_description' => $request->room_description[$item],
'amendities' => implode($request->amendities),
'hotel_id' => $hotel->id,
);
dd($data2);
Rooms::insert($data2);
}
impoding Amendities array saves the data as a string but i am trying to get the values as an array.
u need to prepare a datasets to insert multiple record
so u can try like this
$data2 = [];
foreach ($request->room_type as $item => $v) {
$opt = array(
'room_type' => $request->room_type[$item],
'no_of_pax' => $request->no_of_pax[$item],
'no_of_pax_children' => $request->no_of_pax_children[$item],
'cost_per_adult' => $request->cost_per_adult[$item],
'cost_per_child' => $request->cost_per_child[$item],
'room_description' => $request->room_description[$item],
'amendities' => json_encode($request->amendities),
'hotel_id' => $hotel->id,
);
array_push($data2,$opt);
}
Rooms::insert($data2);
Thank you for the help guys this is final solution which worked for as per your help
foreach ($request->room_type as $item => $v) {
$opt = array(
'room_type' => $request->room_type[$item],
'no_of_pax' => $request->no_of_pax[$item],
'no_of_pax_children' => $request->no_of_pax_children[$item],
'cost_per_adult' => $request->cost_per_adult[$item],
'cost_per_child' => $request->cost_per_child[$item],
'room_description' => $request->room_description[$item],
'amendities' => json_encode($request->amendities),
'hotel_id' => $hotel->id,
);
array_push($data2, $opt);
}
Rooms::insert($data2);
Thank you for your help all of you!

How to add months dynamically which is stored in database as a header in excel file while exporting using laravel?

Suppose I have items in database which is stored from an Excel file. All the items should be below the header of the months. I have also stored months from the file in the database. So, I want those months to be the header of those items and it's related records. In simple words, I want the header to be dynamic. This is what I have done.
I have tried many code scripts but nothing works. Like Laravel, Excel etc. Can anyone suggest me a good approach?
public function test(){
$data = Item::where('category_id',7)->get()->toArray();
$data2 = month::all();
$itemsArray[] = ['Category Id','Item Name','Created At','Updated At'];
foreach ($data as $value) {
// dd($value);
$itemsArray[] = array(
'Category Id' => $value['category_id'],
'Item Name' => $value['name'],
'Created At' => $value['created_at'],
'Updated At' => $value['updated_at'],
);
}
// Generate and return the spreadsheet
Excel::create('Items', function($excel) use ($itemsArray) {
// Set the spreadsheet title, creator, and description
$excel->setTitle('Items');
// Build the spreadsheet, passing in the items array
$excel->sheet('Items', function($sheet) use ($itemsArray) {
$cellRange = 'A1:D1';
// $spreadsheet->getActiveSheet()->getStyle('A1:D4')
// ->getAlignment()->setWrapText(true);
$sheet->getStyle($cellRange)->getFont()->setBold( true );
$sheet->getStyle($cellRange)->getFont()->setSize( '15' );
$sheet->setBorder($cellRange, 'thick' );
$sheet->getStyle($cellRange)->applyFromArray(array(
'fill' => array(
// 'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'A5D9FF')
)
));
$sheet->fromArray($itemsArray, null, 'A1', false, false);
});
$excel->setCreator('Laravel')->setCompany('Dev505');
$excel->setDescription('Items file');
})->download('xlsx');
}
I need help for getting the actual result.
Akhtar i suggest use to kindly install the Carbon package
https://carbon.nesbot.com/docs/
Try by updating the below code.
$data = Item::where('category_id',7)->get(); // removed toArray()
$data2 = month::all();
$itemsArray[] = ['Category Id','Item Name','Created At','Updated At'];
foreach ($data as $key=>$value) {
$itemsArray[] = array(
'month' => Carbon::now()->addMonth($key)->format('m-Y');
'Category Id' => $value['category_id'],
'Item Name' => $value['name'],
'Created At' => $value['created_at'],
'Updated At' => $value['updated_at'],
);
}
This is the actual code which I have used for excel file. I have solved my problem. Thanks and yeah I am posting this code, if anyone can get help from it.
public function export(){
$data = Category::all();
foreach ($data as $value) {
$value['items'] = Item::where('category_id',$value['id'])->get();
foreach ($value['items'] as $vl) {
$vl['record'] = Record::where('item_id',$vl['id'])->get();
}
}
$data2 = month::pluck('id','month');
foreach ($data2 as $key => $value) {
$m[] = $key;
}
array_unshift($m, 'Categories'); //Insert new element at the start of array
array_push($m, 'Total');
$itemsArray[] = $m;
foreach ($data as $value) {
$itemsArray[] = array(
$itemsArray[0][0] => $value['name'],
// $itemsArray[0][13] => 'Total',
);
foreach ($value['items'] as $val) {
$records_array = [];
$i = 0;
foreach ($val['record'] as $val5) {
$recordval = $val5['value'];
$records_array[$i] = $val5['value'];
$i++;
}
$itemsArray[] = array(
$itemsArray[0][0] => $val['name'],
$itemsArray[0][1] => $records_array[0],
$itemsArray[0][2] => $records_array[1],
$itemsArray[0][3] => $records_array[2],
$itemsArray[0][4] => $records_array[3],
$itemsArray[0][5] => $records_array[4],
$itemsArray[0][6] => $records_array[5],
$itemsArray[0][7] => $records_array[6],
$itemsArray[0][8] => $records_array[7],
$itemsArray[0][9] => $records_array[8],
$itemsArray[0][10] => $records_array[9],
$itemsArray[0][11] => $records_array[10],
$itemsArray[0][12] => $records_array[11],
// $itemsArray[0][13] => 'Total',
);
}
}
// Generate and return the spreadsheet
Excel::create('Items', function($excel) use ($itemsArray) {
// Set the spreadsheet title, creator, and description
$excel->setTitle('Items');
// Build the spreadsheet, passing in the items array
$excel->sheet('Items', function($sheet) use ($itemsArray) {
$cellRange = 'A1:M1';
$sheet->getStyle($cellRange)->getFont()->setBold( true );
$sheet->getStyle($cellRange)->getFont()->setSize( '12' );
$sheet->setBorder($cellRange, 'thin' );
$sheet->getStyle($cellRange)->applyFromArray(array(
'fill' => array(
// 'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'A5D9FF')
)
));
$sheet->fromArray($itemsArray, null, 'A1', false, false);
});
$excel->setCreator('Laravel')->setCompany('Dev505');
$excel->setDescription('Items file');
})->download('xlsx');
}

insert batch codelgniter Unknown column 'Array' in 'field list'

I am beginner in CI. I am getting an error in insert_batch function in CodeIgniter. When I insert array into insert_batch I get this error
Unknown column 'Array' in 'field list'
and
Array to string conversion
I've done many solutions but still get this error,
Can anyone give me an idea?
thanks in advance
in my views
<input type="text" name="companionship[]"> and so forth.
controller
public function addstatistics()
{
$i =0;
foreach($_POST['companionship_id'] as $companionship_id):
$value1[$i++] = array(
'companionship_id'=> $companionship_id
);
endforeach;
foreach($_POST['zone_id'] as $zone_id):
$value2[$i++] = array(
'zone_id'=> $zone_id
);
endforeach;
foreach($_POST['district_id'] as $district_id):
$value3[$i++] = array(
'district_id'=> $district_id
);
endforeach;
foreach($_POST['area_id'] as $area_id):
$value4[$i++] = array(
'area_id'=> $area_id
);
endforeach;
foreach($_POST['baptism'] as $baptism):
$value5[$i++] = array(
'baptism'=> $baptism
);
endforeach;
foreach($_POST['confirm'] as $confirm):
$value6[$i++] = array(
'confirm'=> $confirm
);
endforeach;
foreach($_POST['ibd'] as $ibd):
$value7[$i++] = array(
'ibd'=> $ibd
);
endforeach;
foreach($_POST['iasm'] as $iasm):
$value8[$i++] = array(
'iasm'=>$iasm
);
endforeach;
foreach($_POST['ni'] as $ni):
$value9[$i++] = array(
'ni'=>$ni
);
endforeach;
foreach($_POST['ph'] as $ph):
$value10[$i++] = array(
'ph'=>$ph
);
endforeach;
foreach($_POST['wh'] as $wh):
$value11[$i++] = array(
'wh'=>$wh
);
endforeach;
$this->my_model->addstatistics($value1,$value2,$value3,$value4, $value5,$value6,$value7,$value8,$value9,$value10,$value11);
}
MODEL function
addstatistics($value1,$value2,$value3,$value4,$value5, $value6,$value7,$value8,$value9,$value10,$value11)
{
$data = array(
'companionship_id' => $value1,
'zone_id' => $value2,
'district_id' => $value3,
'area_id' => $value4,
'baptism' => $value5,
'confirm' => $value6,
'ibd' => $value7,
'iasm' => $value8,
'ni' => $value9,
'ph' => $value10,
'wh' => $value11
);
$row = array();
$columns = array();
for($x=0; $x<count($data); $x++)
{
$row = array(
'companionship_id'=> $value1,
'zone_id'=> $value2,
'district_id'=> $value3,
'area_id'=> $value4,
'baptism'=> $value5,
'confirm'=> $value6,
'ibd'=> $value7,
'iasm'=> $value8,
'ni'=> $value9,
'ph'=> $value10,
'wh'=> $value11,
'year'=> date('Y'),
'month'=> date('M'),
'week' => weekdate(),
'created_by'=> $this->session->userdata('login_id')
);
array_push($columns, $row);
$rows = array();
}
//printA($columns);
$query= $this->db->insert_batch('monthly_statistics', $columns);
}
Can anybody give me idea on how can i solve this problem?
Try this.
public function addstatistics($value1,$value2,$value3,$value4,$value5, $value6,$value7,$value8,$value9,$value10,$value11)
{
$data = array(
'companionship_id' => $value1,
'zone_id' => $value2,
'district_id' => $value3,
'area_id' => $value4,
'baptism' => $value5,
'confirm' => $value6,
'ibd' => $value7,
'iasm' => $value8,
'ni' => $value9,
'ph' => $value10,
'wh' => $value11
);
$row = array();
$columns = array();
for($x=0; $x<count($data); $x++)
{
$row = array(
'companionship_id'=> $data['companionship_id'][$x]['companionship_id'],
'zone_id'=> $data['zone_id'][$x]['zone_id'],
'district_id'=> $data['district_id'][$x]['district_id'],
'area_id'=> $data['area_id'][$x]['area_id'],
'baptism'=> $data['baptism'][$x]['baptism'],
'confirm'=> $data['confirm'][$x]['confirm'],
'ibd'=> $data['ibd'][$x]['ibd'],
'iasm'=> $data['iasm'][$x]['iasm'],
'ni'=> $data['ni'][$x]['ni'],
'ph'=> $data['ph'][$x]['ph'],
'wh'=> $data['wh'][$x]['wh'],
'year'=> date('Y'),
'month'=> date('M'),
'week' => weekdate(),
'created_by'=> $this->session->userdata('login_id')
);
array_push($columns, $row);
$rows = array();
}
//printA($columns);
$query= $this->db->insert_batch('monthly_statistics', $columns);
}
after a few hours of pondering, I already fix the errors
and now it working fine
here is the code
public function mymethod()
{
$companionship_id = $this->input->post('companionship_id[]');
$zone_id = $this->input->post('zone_id[]');
$district_id = $this->input->post('district_id[]');
$area_id = $this->input->post('area_id[]');
$baptism = $this->input->post('baptism[]');
$confirm = $this->input->post('confirm[]');
$ibd = $this->input->post('ibd[]');
$iasm = $this->input->post('iasm[]');
$ni = $this->input->post('ni[]');
$ph = $this->input->post('ph[]');
$wh = $this->input->post('wh[]');
$value = array();
for($i=0; $i<count($companionship_id); $i++)
{
$value[$i] = array(
'companionship_id' => $companionship_id[$i],
'zone_id' => $zone_id[$i],
'district_id' => $district_id[$i],
'area_id' => $area_id[$i],
'baptism' => $baptism[$i],
'confirm' => $confirm[$i],
'ibd' => $ibd[$i],
'iasm' => $iasm[$i],
'ni' => $ni[$i],
'ph' => $ph[$i],
'wh' => $wh[$i]
);
}
$this->db->insert_batch('monthly_statistics',$value);
$this->session->set_flashdata("success",alert("alert-success","Successfully Inserted"));
redirect(base_url('to_url'));
exit();
}

Laravel 4 - Return the id of the current insert

I have the following query
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
return $results;
}
How would i return the id of the row just inserted?
Cheers,
Instead of doing a raw query, why not create a model...
Call it Conversation, or whatever...
And then you can just do....
$result = Conversation::create(array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now ))->id;
Which will return an id...
Or if you're using Laravel 4, you can use the insertGetId method...In Laravel 3 its insert_get_id() I believe
$results = DB::table('pm_conversations')->insertGetId(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
This method requires that the id of the table be auto-incrementing, so watch out for that...
The last method, is that you can just return the last inserted mysql object....
Like so...
$result = DB::connection('mysql')->pdo->lastInsertId();
So if you choose that last road...
It'll go...
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
$theid= DB::connection('mysql')->pdo->lastInsertId();
return $theid;
}
I would personally choose the first method of creating an actual model. That way you can actually have objects of the item in question.
Then instead of creating a model and just save()....you calll YourModel::create() and that will return the id of the latest model creation
You can use DB::getPdo()->lastInsertId().
Using Eloquent you can do:
$new = Conversation();
$new->currentId = $currentId;
$new->toUserId = $toUserId;
$new->ip = Request::getClientIp();
$new->time = $now;
$new->save();
$the_id = $new->id; //the id of created row
The way I made it work was I ran an insert statement, then I returned the inserted row ID (This is from a self-learning project to for invoicing):
WorkOrder::create(array(
'cust_id' => $c_id,
'date' => Input::get('date'),
'invoice' => Input::get('invoice'),
'qty' => Input::get('qty'),
'description' => Input::get('description'),
'unit_price' => Input::get('unit_price'),
'line_total' => Input::get('line_total'),
'notes' => Input::get('notes'),
'total' => Input::get('total')
));
$w_id = WorkOrder::where('cust_id', '=', $c_id)->pluck('w_order_id');
return $w_id;

Resources