How to get cart data inside array in codeigniter - php

i have 2 products in my cart session. and want me to combine in array data_order. but read only 1 product. actually this data I will send in an email so from that I make the format of the data like this.
my controller :
foreach ($this->cart->contents() as $item){
if($item['diskon'] == "0"){
$harga_before = $item['before'];
$harga_after = $item['price'];
}else{
$harga_before = $item['before'];
$harga_after = $item['price'];
}
foreach ($this->cart->product_options($item['rowid']) as $option_name => $option_value){
if(empty($option_value)){
$option_size = "";
$option_color = "";
}else{
$option = $item['options'];
$option_size = $option['Size'];
$option_color = $option['Warna'];
}
}
$data = array(
'inv' => $invoice,
'tglOrdercs' => date('d F Y H:i:s'),
'tglExp' => $date_maju,
'nmlkp' => $nmlkpi,
'almtkp' => $address,
'noTelp' => $notelp271,
'methode' => $method,
'bnk_option' => $banking_select,
'data_order' => array(
'nama_produk' => $item['name'],
'artikel' => $item['artikel'],
'diskon' => $item['diskon'],
'ukuran' => $option_size,
'warna' => $option_color,
'qty' => $item['qty'],
'harga_fix' => $harga_after,
'harga_before' => $harga_before,
),
);
}
my result :
Array(
[inv] => STJOHB9261JR
[tglOrdercs] => 28 September 2017 11:23:33
[tglExp] => 28 September 2017 21:23:33
[nmlkp] => danny setyawan
[almtkp] => Perum puspa sari H22 sidoarjo
[noTelp] => 089263423647
[methode] => Transfer
[bnk_option] => Bank BNI
[data_order] => Array
(
[nama_produk] => Sonic TL Brown
[artikel] => CH2002-831
[diskon] => 40
[ukuran] => 39
[warna] => Coklat
[qty] => 2
[harga_fix] => 125340
[harga_before] => 208900
)
)
ignore ">", this result from browser console.

Related

Writing a HTML string content with array values in Laravel Controller

What I'm trying to accomplish is to write a html string in a controller with array values being looped in it. So for example;
$content = "Your store, at location A, has these items added to them". add array loop here. "Do take note!";
My array would be as such
array (
0 =>
array (
'id' => '5db29b6d31c391731239bbdf',
'name' => 'Diamond bracelet (sample)',
'tags' =>
array (
0 => 'female',
1 => 'jewelry',
),
'category' => 'Accessories',
'sku' => '1029EHW',
'priceType' => 'Fixed',
'unitPrice' => 190,
'cost' => 90,
'trackStockLevel' => true,
'isParentProduct' => false,
),
1 =>
array (
'id' => '5db29b6d31c391731239bbdb',
'name' => 'Long-sleeved shirt(sample)(M)',
'tags' =>
array (
0 => 'tops',
1 => 'cotton',
),
'category' => 'Women\'s Apparel',
'sku' => 'ABC1234-M',
'priceType' => 'Fixed',
'unitPrice' => 47.170000000000002,
'cost' => 20,
'trackStockLevel' => true,
'isParentProduct' => false,
'parentProductId' => '5db29b6d31c391731239bbd4',
'variationValues' =>
array (
0 =>
array (
'variantGroupId' => '5db29b6d31c391731239bbd5',
'value' => 'M',
),
),
),
)
note that the array can have many instances of product_name and sku, or can have none.
How do i populate this in my string to be like;
$content = "Your store, at location A, has these items added to them, 1) asd, 2)def, 3)asf . Do take note!
Try this, I've used \sprintf for ease, check if the output serves your purpose.
<?php
function stringMethod(): string
{
$count = 0;
$arrayString = [];
$array = [['product_name' => 'abc', 'product_sku' => 'def'],['product_name' => 'abc', 'product_sku' => 'asd']];
foreach ($array as $value){
$count++;
$arrayString[] = sprintf('%s)%s', $count, $value['product_sku']);
}
$string = \implode(',', $arrayString);
return \sprintf("Your store, at location A, has these items added to them %s Do take note!", $string);
}
echo stringMethod();
Hope this will help you. try to do it in less number of lines
$content = "Your store, at location A, has these items added to them, ";
$productArray = array (0 => array ('id' => '5db29b6d31c391731239bbdf','name' => 'Diamond bracelet (sample)','tags' => array (0 => 'female',1 => 'jewelry',),'category' => 'Accessories','sku' => '1029EHW','priceType' => 'Fixed','unitPrice' => 190,'cost' => 90,'trackStockLevel' => true,'isParentProduct' => false,),1 => array ('id' => '5db29b6d31c391731239bbdb','name' => 'Long-sleeved shirt(sample)(M)','tags' => array (0 => 'tops',1 => 'cotton',),'category' => 'Women\'s Apparel','sku' => 'ABC1234-M','priceType' => 'Fixed','unitPrice' => 47.170000000000002,'cost' => 20,'trackStockLevel' => true,'isParentProduct' => false,'parentProductId' => '5db29b6d31c391731239bbd4','variationValues' => array (0 => array ('variantGroupId' => '5db29b6d31c391731239bbd5','value' => 'M'))));
foreach ($productArray as $key => $product) {
$content .= ($key+1).') '.$product['name'];
if (count($productArray)-1!=$key) {
$content .= ', ';
}
}
$content .= ". Do take note!";
$content = "Your store, at location A, has these items added to them,". $this->getItemList($collection) .". Do take note!"
# Somewhere else in the controller
protected function getItemList(Collection $collection): string
{
return $collection->pluck('name')
->merge($collection->pluck('sku'))
->map(function($item, $key) {
return ($key + 1) . ') ' . $item;
})
->implode(', ');
}
An easy solution would be
$content = "Your store, at location A, has these items added to them";
$array = array(0=>["product_name" => "abc", "product_sku" => "def"], 1=>['product_name' => 'kdkf', 'product_sku'=> 'ljbkj']);
for($i = 0; $i<count($array); $i++){
$content .= ($i+1).") ".$array[$i]['product_name].' '.$array[$i]['product_sku'].', ';
}
$content .= "Do take note.";
This way you're just constantly concatonating the string value in separate parts instead of trying to inject it in the middle of the parent string.
not tested, may be syntax errors

Codeigniter Model Undefined Index on Array

I'm trying to use Codeigniter to update my value once the user had submitted the form. But unfortunately, there was an error of undefined index for few of the variable which I store in an array.
Below is the Code that I use to pass from Controller to the Model
Controller Code :
$prep_data = array(
'full_name' => $this->input->post('full_name'),
'nric' => $this->input->post('nric'),
'dob' => $this->input->post('dob'),
'mobile_phone' => $this->input->post('mobile_phone'),
'email' => $this->input->post('email'),
'address_line_1' => $this->input->post('address_line_1'),
'address_line_2' => $this->input->post('address_line_2'),
'postcode' => $this->input->post('postcode'),
'state' => $this->input->post('state'),
'current_brand' => $this->input->post('current_brand'),
'pregnant' => $isPregnant, //Edit by Marcus
'breastfeeding' => $isBreastfeeding, //Added by Marcus
'child_full_name' => $this->input->post('child_full_name'),
'child_dob' => $this->input->post('child_dob'),
'child_current_brand' => $this->input->post('child_current_brand'),
'expected_give_birth_date' => $this->input->post('expected_give_birth_date'),
'image' => '',
'quantity_purchase' => $this->input->post('quantity_purchase'),
'foc_amount' => $this->input->post('foc_amount'),
'marketing_opt' => $this->input->post('marketing_opt'),
'centre_id' => get_cookie('abbott_centre', TRUE),
'user_id' => $this->session->id,
'sampling_day' => $centre_data['sampling_day'],
'created_at' => $datetime,
'updated_at' => $datetime
);
$this->entry_model->update_entry($prep_data);
Model Code :
function update_entry($data){
echo print_r($data);
if(!empty($data['full_name'])) $this->db->set('full_name', $data['full_name']);
if(!empty($data['nric'])) $this->db->set('nric', $data['nric']);
if(!empty($data['dob'])) $this->db->set('dob', $data['dob']);
if(!empty($data['mobile_phone'])) $this->db->set('mobile_phone', $data['mobile_phone']);
if(!empty($data['email'])) $this->db->set('email', $data['email']);
if(!empty($data['address_line_1'])) $this->db->set('address_line_1', $data['address_line_1']);
if(!empty($data['address_line_2'])) $this->db->set('address_line_2', $data['address_line_2']);
if(!empty($data['postcode'])) $this->db->set('postcode', $data['postcode']);
if(!empty($data['state'])) $this->db->set('state', $data['state']);
if(!empty($data['current_brand'])) $this->db->set('current_brand', $data['current_brand']);
if(!empty($data['pregnant'])){ //Fix by Marcus
$this->db->set('pregnant', $data['pregnant']);
}else {
$this->db->set('pregnant', 0);
}
if(!empty($data['breastfeeding'])){ //Fix by Marcus
$this->db->set('breastfeeding', $data['breastfeeding']);
}
else {
$this->db->set('breastfeeding', 0);
}
if(!empty($data['expected_give_birth_date'])) $this->db->set('expected_give_birth_date', $data['expected_give_birth_date']);//Fix by Marcus
if(!empty($data['child_full_name'])) $this->db->set('child_full_name', $data['child_full_name']);
if(!empty($data['child_dob'])) $this->db->set('child_dob', $data['child_dob']);
if(!empty($data['child_current_brand'])) $this->db->set('child_current_brand', $data['child_current_brand']);
if(!empty($data['image'])) $this->db->set('image', $data['image']);
if(isset($data['quantity_purchase'])) $this->db->set('quantity_purchase', $data['quantity_purchase']);
if(isset($data['foc_amount'])) $this->db->set('foc_amount', $data['foc_amount']);
if(!empty($data['marketing_opt'])) $this->db->set('marketing_opt', $data['marketing_opt']);
if(!empty($data['centre_id'])) $this->db->set('centre_id', $data['centre_id']);
if(!empty($data['user_id'])) $this->db->set('user_id', $data['user_id']);
if(!empty($data['created_at'])) $this->db->set('created_at', $data['created_at']);
if(!empty($data['updated_at'])) $this->db->set('updated_at', $data['updated_at']);
$this->db->where('id', $data['id']);
$this->db->update('entry');
}
Other $data[] value had no problem but only the 'pregnant' and 'breastfeeding' had the error on Undefined Index. I did try to print_r to show the $data value and all are seem to be alright.
Below are the output :
Array ( [full_name] => e2e [nric] => 123 [dob] => 2019-07-09 [mobile_phone] => 1231231231 [email] => [address_line_1] => [address_line_2] => [postcode] => [state] => [current_brand] => [pregnant] => 0 [breastfeeding] => 1 [child_full_name] => [child_dob] => 0000-00-00 [child_current_brand] => [expected_give_birth_date] => 2019-07-09 [image] => [quantity_purchase] => 123123 [foc_amount] => 123 [sampling_day] => [updated_at] => 2019-07-10 19:27:43 [id] => 8 ) 1Array ( [image] => 8_20190710_192743.jpg [id] => 8 ) 1
What will be the caused for this 'pregnant' and 'breastfeeding' array? As it keeps getting NULL as a return.
Thanks
You need to use isset() to check either index set or not like
$isPregnant = 0;
$isBreastfeeding = 0;
if(isset($_POST['pregnant']) && $_POST['pregnant'] == 1)
{
$isBreastfeeding = 0;
$isPregnant = 1; //Is breastfeeding selected
}
if(isset($_POST['breastfeeding']) && $_POST['breastfeeding'] == 1)
{
$isPregnant = 0;
$isBreastfeeding = 1; //Is breastfeeding selected
}

Unable to insert data into database using codeigniter

I want to insert data into my database. I am using codeigniter framework to build my app.
When I click on submit button,It don't give any error just reload the same page and data in not inserted in database.
Following my code to insert data into database -
public function addSale($saleDetails = array(), $items = array(), $warehouse_id)
{
foreach($items as $data){
$product_id = $data['product_id'];
$product_quantity = $data['quantity'];
$this->updateProductQuantity($product_id, $warehouse_id, $product_quantity);
}
// sale data
$saleData = array(
'reference_no' => $saleDetails['reference_no'],
'warehouse_id' => $warehouse_id,
'biller_id' => $saleDetails['biller_id'],
'biller_name' => $saleDetails['biller_name'],
'customer_id' => $saleDetails['customer_id'],
'customer_name' => $saleDetails['customer_name'],
'date' => $saleDetails['date'],
'note' => $saleDetails['note'],
'internal_note' => $saleDetails['internal_note'],
'inv_total' => $saleDetails['inv_total'],
'total_tax' => $saleDetails['total_tax'],
'total' => $saleDetails['total'],
'total_tax2' => $saleDetails['total_tax2'],
'tax_rate2_id' => $saleDetails['tax_rate2_id'],
'inv_discount' => $saleDetails['inv_discount'],
'discount_id' => $saleDetails['discount_id'],
'user' => $saleDetails['user'],
'shipping' => $saleDetails['shipping']
);
if($this->db->insert('sales', $saleData)) {
$sale_id = $this->db->insert_id();
$addOn = array('sale_id' => $sale_id);
end($addOn);
foreach ( $items as &$var ) {
$var = array_merge($addOn, $var);
}
if($this->db->insert_batch('sale_items', $items)) {
return true;
}
}
return false;
}
Based on https://ellislab.com/codeigniter/user-guide/database/examples.html , it seems to me, that you are missing a line -> $this->db->insert('sales', $saleData); . You do have it inside an if statement, but if statement will not execute it as a code, but check if it returns true.
$saleData = array(
'reference_no' => $saleDetails['reference_no'],
'warehouse_id' => $warehouse_id,
'biller_id' => $saleDetails['biller_id'],
'biller_name' => $saleDetails['biller_name'],
'customer_id' => $saleDetails['customer_id'],
'customer_name' => $saleDetails['customer_name'],
'date' => $saleDetails['date'],
'note' => $saleDetails['note'],
'internal_note' => $saleDetails['internal_note'],
'inv_total' => $saleDetails['inv_total'],
'total_tax' => $saleDetails['total_tax'],
'total' => $saleDetails['total'],
'total_tax2' => $saleDetails['total_tax2'],
'tax_rate2_id' => $saleDetails['tax_rate2_id'],
'inv_discount' => $saleDetails['inv_discount'],
'discount_id' => $saleDetails['discount_id'],
'user' => $saleDetails['user'],
'shipping' => $saleDetails['shipping']
);
$this->db->insert('sales', $saleData);
This should work. You can also check if it succeeds like this ->
return ($this->db->affected_rows() != 1) ? false : true;

how to find a element in a nested array and get its sub array index

when searching an element in a nested array, could i get back it's 1st level nesting index.
<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k, $search_query){
global $cnt;
if($v == $search_query){
/* i want the sub array index to be returned */
}
}
?>
i.e to say, if i'am searching 'victor', i would like to have 'dep1' as the return value.
Could anyone help ??
Try:
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($coll), RecursiveIteratorIterator::SELF_FIRST);
/* These will be used to keep a record of the
current parent element it's accessing the childs of */
$parent_index = 0;
$parent = '';
$parent_keys = array_keys($coll); //getting the first level keys like dep1,dep2
$size = sizeof($parent_keys);
$flag=0; //to check if value has been found
foreach ($iter as $k=>$val) {
//if dep1 matches, record it until it shifts to dep2
if($k === $parent_keys[$parent_index]){
$parent = $k;
//making sure the counter is not incremented
//more than the number of elements present
($parent_index<$size-1)?$parent_index++:'';
}
if ($val == $name) {
//if the value is found, set flag and break the loop
$flag = 1;
break;
}
}
($flag==0)?$parent='':''; //this means the search string could not be found
echo 'Key = '.$parent;
Demo
This works , but I don't know if you are ok with this...
<?php
$name = 'linda';
$col1=array ( 'dep1' => array ( 'fy' => array ( 0 => 'john', 1 => 'johnny', 2 => 'victor', ), 'sy' => array ( 0 => 'david', 1 => 'arthur', ), 'ty' => array ( 0 => 'sam', 1 => 'joe', 2 => 'victor', ), ), 'dep2' => array ( 'fy' => array ( 0 => 'natalie', 1 => 'linda', 2 => 'molly', ), 'sy' => array ( 0 => 'katie', 1 => 'helen', 2 => 'sam', 3 => 'ravi', 4 => 'vipul', ), 'ty' => array ( 0 => 'sharon', 1 => 'julia', 2 => 'maddy', ), ), );
foreach($col2 as $k=>$arr)
{
foreach($arr as $k1=>$arr2)
{
if(in_array($name,$arr2))
{
echo $k;
break;
}
}
}
OUTPUT :
dept2
Demo

CodeIgniter: Populating two tables through two arrays from the same form?

I tried doing the following and surprisingly it only populates the first table (new_guest) while writing only zero values to the other (new_reservation). How can I properly configure this?
Controller:
function guest_checks_in() {
$data_guest = array (
'guest_title' => $this->input->post('guest_title'),
'guest_name' => $this->input->post('guest_name'),
'guest_gender' => $this->input->post('guest_gender'),
'guest_phone' => $this->input->post('guest_phone'),
'guest_email' => $this->input->post('guest_email'),
'guest_address' => $this->input->post('guest_address'),
'guest_province' => $this->input->post('guest_province'),
'guest_country' => $this->input->post('guest_country'),
'guest_postal_code' => $this->input->post('guest_postal_code'),
'guest_dob' => $this->input->post('guest_dob'),
'guest_nic_pp_dl' => $this->input->post('guest_nic_pp_dl')
);
$data_reservation = array (
'room_type' => $this->input->post('room_type'),
'meal_type' => $this->input->post('meal_type'),
'bed_type' => $this->input->post('bed_type'),
'ext_beds' => $this->input->post('ext_beds'),
'number_of_guests' => $this->input->post('number_of_guests'),
'start_date' => $this->input->post('start_date'),
'end_date' => $this->input->post('end_date'),
'reservation_duration' => $this->input->post('reservation_duration'),
'room_number' => $this->input->post('room_number'),
'total' => $this->input->post('total')
);
$this->reservations_model->add_guests($data_guest);
$this->reservations_model->add_reservations($data_reservation);
$this->confirm_check_in();
}
Model:
class Reservations_model extends CI_Model {
function add_guests($data_guest) {
$this->db->insert('new_guest', $data_guest);
return;
}
function add_reservations($data_reservation) {
$this->db->insert('new_reservation', $data_reservation);
return;
}
}
it will be good if you use transaction. if data in both tables must be entered.
function guest_checks_in() {
$data_guest = array (
'guest_title' => $this->input->post('guest_title'),
'guest_name' => $this->input->post('guest_name'),
'guest_gender' => $this->input->post('guest_gender'),
'guest_phone' => $this->input->post('guest_phone'),
'guest_email' => $this->input->post('guest_email'),
'guest_address' => $this->input->post('guest_address'),
'guest_province' => $this->input->post('guest_province'),
'guest_country' => $this->input->post('guest_country'),
'guest_postal_code' => $this->input->post('guest_postal_code'),
'guest_dob' => $this->input->post('guest_dob'),
'guest_nic_pp_dl' => $this->input->post('guest_nic_pp_dl')
);
$data_reservation = array (
'room_type' => $this->input->post('room_type'),
'meal_type' => $this->input->post('meal_type'),
'bed_type' => $this->input->post('bed_type'),
'ext_beds' => $this->input->post('ext_beds'),
'number_of_guests' => $this->input->post('number_of_guests'),
'start_date' => $this->input->post('start_date'),
'end_date' => $this->input->post('end_date'),
'reservation_duration' => $this->input->post('reservation_duration'),
'room_number' => $this->input->post('room_number'),
'total' => $this->input->post('total')
);
$this->reservations_model->add_all_guests($data_guest,$data_reservation);
$this->confirm_check_in();
}
in model
function add_all_guests($data_guest,$data_reservation) {
$this->db->trans_begin();
$this->db->insert('new_guest', $data_guest);
$this->db->insert('new_reservation', $data_reservation);
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
return false;
}
else
{
$this->db->trans_commit();
return true;
}
}

Categories