Compare data tems in a cart funtion - php

Is there a way to compare two attributes in the cart function?
$data = array(
'id' => $id,
'qty' => $qty,
'price' => $price,
'name' => $name,
'stock' =>$quan
);
So if I have to compare the qty and stock elements,how should I implement them at the controller?
Sorry for the late submission. Here is the controller code:
function update_c()
{
$data = $_REQUEST;
foreach ($this->cart->contents() as $items)
{
$name = $items['name'];
$quantity = $items['qty'];
$price = $items['price'];
$sub = $items['subtotal'];
$total = $this->cart->total();
$id = $items['id'];
$quan=$items['stock'];
if($items['quantity']<=$items['quan'])
{
$this->data['err_message'] = 'Your cart is added!';
$this->cart->update($data);
redirect($_SERVER['HTTP_REFERER']);
}
else
{
$this->data['err_message'] = 'quantity mismatch';
}
}
}

$data is the variable passed to your view from the controller so i am assuming you are already in the controller. If that's the case why don't you compare before putting them in the variable, but if that isn't the case a simple if statement with the array will suffice
if($data["qty"]==$data["stock"]){
//Some statements
}
I hope i'm on the right course. Let me know what happens

Related

php codeigniter i want to redirect this function print_view and also pass the data

php codeigniter i want to redirect this function print_view and also pass the data $this->db->insert('invoice_main',$datas);$result = $this->db->insert_id();
Public function insert_invoice(){
$item_name = $_POST['item'];
$rate = $_POST['rate'];
$quantity = $_POST['quantity'];
$tax = $_POST['tax'];
$amount = $_POST['amount'];
$invoice_id = $this->input->post('invoice_id');
//$invoice_id++;
$datas = array(
'user_id' => $this->session->userdata('user_id'),
'invoice_id' => $this->input->post('invoice_id'),
'pt_opnum' => $this->input->post('pt_opnum'),
'pt_uhid' => $this->input->post('pt_uhid'),
'doc_name' => $this->input->post('doc_name'),
'status'=>1
);
$this->db->insert('invoice_main',$datas);
$result = $this->db->insert_id();
for ($i=0; $i <count($item_name) ; $i++) {
$data=array(
'invoice_id' =>$invoice_id,
'pt_name'=> $this->input->post('pt_opnum'),
'date'=>date('d-m-Y'),
'name'=>$item_name[$i],
'rate'=>$rate[$i],
'quantity'=>$quantity[$i],
'tax'=>$tax[$i],
'amount'=>$amount[$i],
'sub_total'=>$_POST['sub_total'],
'o_tax'=>$_POST['o_tax'],
'grand_total'=>$_POST['grand_total'],
'status'=>1
);
$this->db->insert('invoice_details',$data);
}
return($this->db->affected_rows()!=1)?false:true;
$this->print_view($result);
}
public function print_view($result){
redirect(base_url()."invoice/print_view/".$result);
}
You can pass the any data with flashdata.
$this->session->set_flashdata('something',$result);
On the other page you can access it
$something = $this->session->flashdata('something);
But on your case you don't have to use flash data, you can get the params from url and you can search on your DB.

Insert Batch php mysql with check duplicate and sum values of field duplicate

i have 1 million data using foreach.
ex table:
table
the data
data
i want to inserting that's data using batch/multipleinsert, but i have problem when i got duplicate data. if data duplicate i want the field amount will sum and update amount field with sum amount duplicated data.
this is my code before
<?php
foreach ($data_transaksi as $key)
{
if($key['STATUS_COA'] != $key['CHART_OF_ACCOUNT_STATUS'])
{
if($key['ACCOUNT_CATEGORY_CODE'] == '9')
{
$amount = round($key['AMOUNT'],2);
}
else
{
$amount = round($key['AMOUNT'],2) *-1;
}
}
else
{
if($key['ACCOUNT_CATEGORY_CODE'] == '9')
{
$amount = round($key['AMOUNT'],2)*-1;
}
else
{
$amount = round($key['AMOUNT'],2);
}
}
$dt_exsis = $this->ledger_model->cek_data_coa_exsis($key['COA_CODE'],$modul,$ID_USER);
if(empty($dt_exsis['id']))
{
//TRYINSERTINGBATCH
// $datainsert[] = '('.$key['COA_CODE'].','.$amount.','.$ID_USER.',"'.$modul.'")';
// $test = $key['COA_CODE'];
$datainput = array(
'COA_CODE' => $key['COA_CODE'],
'AMOUNT' => $amount,
'MODUL' => $modul,
'USER_ID' => $ID_USER
);
$this->ledger_model->save_rows_to_table($datainput,'finance_lapkue_temp');
}
else
{
$amount_fix = $amount + $dt_exsis['AMOUNT'];
$data=array(
'AMOUNT' => $amount_fix
);
$this->ledger_model->edit_rows_to_table_where($data,'finance_lapkue_temp','id',$dt_exsis['id']);
// $q = "UPDATE finance_lapkue_temp set AMOUNT = '$amount_fix' where id = '".$dt_exsis['id']."'";
// $this->db->query($q);
}
// $data_amount[$key['COA_CODE']] += $amount;
}
?>
if i using this code, the proccess so slow
Good option will to pass only data to DB that you want to insert. All the data cleaning task can be done in controller.
// Create a data array and add all info
$data = [];
//if user does not exist add it in array
if (empty($dt_exist($id))) {
$data[$ID_USER] = array(
'COA_CODE' => $key['COA_CODE'],
'AMOUNT' => $amount,
'MODUL' => $modul,
'USER_ID' => $ID_USER
);
}
else {
//if user exist in $data just modify the amount
if (!empty($data[$ID_USER])) {
$data[$ID_USER]['AMOUNT'] += $dt_exsis['AMOUNT'];
}
else {
// if user does not exist in data create add all info
$data[$dt_exsis['ID_USER']] = array(
'COA_CODE' => $dt_exsis['COA_CODE'],
'AMOUNT' => $dt_exsis['amount'],
'MODUL' => $dt_exsis['modul'],
'USER_ID' => $dt_exsis['ID_USER']
);
}
}
This will save multiple calls to DB and at the end you can pass $data and do multiple insert.

Check if array exist by two keys with PHP

I'd like to check if array exist by two keys: id and type
This code just check by id:
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
else {
$type = '';
}
if (array_key_exists($id, $_SESSION['cart'])) {
$_SESSION['cart'][$id]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$id] = $line;
}
I have tried with this code but it doesn't work:
if (array_key_exists($id, $_SESSION['cart']) && array_key_exists($type, $_SESSION['cart'])) {
$_SESSION['cart'][$id]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$id] = $line;
}
$_SESSION['cart'] is an array contains arrays of $line
$line = array(
'id' => $id,
'type' => $type,
'quantity' => $quantity,
'price' => $price,
'picture' => $dish->getPicture()->getWebPath(),
);
This is the output of $_SESSION['cart']:
As you see in th last array with id 55 and type "french bred" , what I'd like to do is to check if th user chose the same product but a with different type so insert new line else if the same product and the same type so just update quantity.
Something like this should do, however the question is too vague and too little code is shown for me to properly understand your problem
$lineExists = false;
foreach($_SESSION['cart'] as $index => $line){
if($line['id'] === $id)
{
$_SESSION['cart'][$index]['quantity'] += $quantity;
$lineExists = true;
}
}
if(!$lineExists)
{
$_SESSION['cart'][] = $newLine;
}
If you want to check if type and id exists then you should do something like this
if (array_key_exists('id', $_SESSION['cart']) && array_key_exists('type', $_SESSION['cart'])) {
// stuff here..
}
if $id is the value of the key id so 'id' => 5 then you should check like this:
if ($_SESSION['cart']['type'] == $id) {
// stuff here
}
Hope this somewhat helps you further!

Array variable is not getting set - PHP Codeigniter

I am trying to set array, but it is not getting set. Everytime the Buy function called, the array gets declared.
This is the function is controller.
public function buy() {
if($this->session->userdata('counter')){
$counter = $this->session->userdata('counter');
$this->session->set_userdata('counter', $counter + 1);
} else {
$this->session->set_userdata('counter', 1);
}
if(isset($bought)){
$name = $this->input->post('name');
$price = $this->input->post('price');
$qty = $this->input->post('qty');
$product = array('name' => $name, 'price' => $price, 'qty'=> $qty);
array_push($bought, $product);
var_dump($bought);
die();
} else {
$bought = array();
redirect("");
}
As you can see, it should remember that $bought is set, but it gets declared anew. For now I
tried to make it global, before "public function __construct()",
tried "if (!empty),
tried to put into session,
tried to find the answer across whole stackoverflow...
Please let me know if additional info needed.
Thanks a lot!
In your code when you are checking for $bought, it is not present so it is going to the else part everytime. Instead define a blank array and then set the values inside it. Try with -
if(isset($_SESSION['bought'])){
$name = $this->input->post('name');
$price = $this->input->post('price');
$qty = $this->input->post('qty');
$product = array('name' => $name, 'price' => $price, 'qty'=> $qty);
array_push($_SESSION['bought'], $product);
var_dump($_SESSION['bought']);
die();
} else {
$_SESSION['bought'] = array();
}
And start the session at top of the page.
I got it working.
I made a workaround with sgt's help, so now my code looks like this:
if($this->session->userdata('bought')){
$name = $this->input->post('name');
$price = $this->input->post('price');
$qty = $this->input->post('qty');
$product = array('name' => $name, 'price' => $price, 'qty'=> $qty);
// please see that here I just returned from old one and added new data to the old one.
// Then I just added the result to the session.
$old_session = $this->session->userdata('bought');
array_push($old_session, $product);
$this->session->set_userdata('bought', $old_session);
redirect("");
} else {
$this->session->set_userdata('bought', array());
}

How to update the value of array in Yii session

I am using "ajaxSubmitButton" to send some values of 3 fields: registrant, product id and quantity to controller (controller name: actionCart). After submitting the button I receive those values in session array what I did successfully. At this point, if I submit same product id but different quantity, I want to update the quantity key with new value. I have done this by php global $_SESSION but can't using Yii session variable.
public function actionCart()
{
if(isset($_POST["Order"])){
$item = $_POST["Order"];
$registration_id = $item["registration_id"];
$this->productId = $item["item"];
$quantity = $item["quantity"];
$quantity = $item["quantity"]=='' ? 1 : $item["quantity"];
$productInfo = Products::model()->findByPk(array('id'=>$this->productId));
$totalPrice = $productInfo->price * $quantity;
$newItem = array("product_id" => $this->productId , "product_name" => $productInfo->name, "quantity" => $quantity,"price" => $productInfo->price,"totalPrice" => $totalPrice);
$session = Yii::app()->session;
$cartArray = $session['cart'];
$searchArrResult = $this->searchSubArray($session['cart'],'product_id',$this->productId);
if (!empty($searchArrResult)) {
/***** this works *****/
foreach ( $_SESSION['cart'] as $key=>$cart ) {
if ( $cart["product_id"] == $this->productId ) {
$_SESSION['cart'][$key]['quantity']=$quantity;
$_SESSION['cart'][$key]['totalPrice']=$totalPrice;
}
}
/***** following commented code does not work *****
*
foreach($session['cart'] as $key=>$cart){
if ($cart["product_id"] == $this->productId){
$session['cart'][$key]['quantity'] == $quantity;
$session['cart'][$key]['totalPrice'] == $totalPrice;
}
}*/
}
else {
$cartArray[] = $newItem;
$session['cart'] = $cartArray;
}
print_r($session['cart']);
//unset(Yii::app()->session['cart']);
}
}
In the above code I marked by commenting where I want to update session values. Please help me someone if it is possible do in yii.
Try this:
$carts = $session['cart'];
foreach($carts as $key=>&$cart){
if ($cart["product_id"] == $this->productId){
$cart['quantity'] == $quantity;
$cart['totalPrice'] == $totalPrice;
}
}
$session['cart'] = $carts;
Yii::app()->session return object of CHttpSession, not reference to $_SESSION.
$carts = $session['cart'] equals operation $carts = $session->get('cart'); (by means magic method __get in CHttpSession) and $session['cart'] = $carts; equals to $session->set('cart', $carts); (by __set)
That's why you can't setting by $session['cart'][$key]['quantity'] = $quantity;
UPDATED full solution (I change logic of saving products - $key = product_id)
public function actionCart()
{
if(isset($_POST["Order"])){
$item = $_POST["Order"];
$registration_id = $item["registration_id"];
$this->productId = $item["item"];
$quantity = empty(intval($item["quantity"])) ? 1 : intval($item["quantity"]);
$productInfo = Products::model()->findByPk(array('id'=>$this->productId));.
if(empty($productInfo))
return false; // or other action
$newItem = array(
"product_id" => $this->productId ,
"product_name" => $productInfo->name,
"quantity" => $quantity,
"price" => $productInfo->price,
"totalPrice" => ($productInfo->price * $quantity)
);
$cartArray = Yii::app()->session['cart'];
$cartArray[$this->productId] = $newItem;
Yii::app()->session['cart'] = $cartArray;
}
}

Categories