increment doesn't apply at the first time - php

i'm newbie in laravel and i'm working on a shop website and i've got stuck in the cart part of the project.
and for that i'm using a pivot table with ManyToMeny relation
the main problem is when i add to the cart for the first time it gives me always one, but in the second time it increments the third time it increments too. i searched in the pivote table structure and i found 1 as a default value.
first add
result of the first add
second add
results of the second add it increments !
i don't know how to change the value of the given 1 in the first. I don't know what to change to make the first add value like the input value.
i think the expected outcome of this code is to increment the value of 0 with the value given by input number
this is my controller
$found = false;
$user = Auth::user();
$product = produit::find($id);
if (!$product || !$user) {
abort(404);
}
if($product->rupture_stock == true){
return redirect()->back()->with('error', 'Rupture de stock');
}
$panier = $user->panier;
foreach ($panier->produits as $pr) {
if ($pr->id == $id){
$found = true;
$qt = $pr->pivot->quantite;
$first_num = $request->get('quantite');
// $first_num = $_POST['quantite'];
$second_num = 0;
$result = '';
// $qt = $_POST['quantite'];
if (is_numeric($first_num) && is_numeric($second_num)) {
$result = $first_num + $second_num;
$qt += $result;
}
$panier->produits()->updateExistingPivot($pr->id, ['quantite' => $qt]);
}
}
if (!$found) {
$panier->produits()->attach($product->id);
}
this is my blade
<form action="{{ url('add/'.$prod->id) }}" method="post" style="margin-bottom:20px" class="cart" id="product_addtocart_form" enctype='multipart/form-data'>
#csrf
<input type="number" value="" name="quantite" class="text" step="1" min="1" max="11" size="4" placeholder="" inputmode="numeric" />
<button style="border-radius: 50px; /*padding:0 20px; margin-left:40px*/" type="submit" name="add-to-cart" value="352" class="single_add_to_cart_button button alt">Ajouter</button>
</form>

You can do it more simple by using syncWithoutDetaching:
$user = Auth::user();
$product = produit::find($id);
if (!$product || !$user) {
abort(404);
}
if($product->rupture_stock == true){
return redirect()->back()->with('error', 'Rupture de stock');
}
$panier = $user->panier;
$panier->produits()->syncWithoutDetaching([$id => ['quantite' => (int)request('quantite')]]);
https://laravel.com/docs/8.x/eloquent-relationships#syncing-associations

Related

How to update database base on laravel checkbox value

I load check boxes from database with they are checked or not,
<div class="row">
<div class="col-xs-12">
<div class="form-group">
#php
$json = $orders->data;
$json = json_decode($json, true);
$products = $json['order_info']['products'];
$data = '';
foreach ($products as $hitsIndex => $hitsValue) {
$data .= $hitsValue['type']. ', ';
}
$data = rtrim($data, ', ');
$agosProducts = Utility::constant('agos_products1');
#endphp
{{Html::validation($orders, 'product')}}
<label for="products" class="control-label">{{Translator::transSmart('app.Products', 'Products')}}</label><br><br>
#foreach($agosProducts as $product)
<label class="control-label "for="{{ $product['type'] }}">
<input id="{{ $product['type'] }}" name="{{ $product['type'] }}" type="checkbox" value="{{ $product['type'] }}"
#foreach ($products as $hitsIndex => $hitsValue)
#if(in_array($hitsValue['type'], $product)) checked=checked #endif
#endforeach
>
{{ $product['name'] }}
</label>
<br>
#endforeach
</div>
</div>
</div>
Now i want to update my database base on checkbox value.
For example if say i load checkbox 1 as checked from database and now it's unchecked i need to update it in database.
This code i can get all the current status of checkbox but i don't know previous values of this. So it hard update statue of current values and add new status in database,
$chks = array('multicolor','resizable','showRuler','namesNumbersEnabled');
foreach ($chks as $chk) {
$product->setAttribute($chk, (Input::has($chk)) ? true : false);
}
This is my json object save in data column
{"user_token":"ad48c412-3866-4ac9-adf6-3328911ae46c",
"order_info":
{"order_id":"CGC12345678","company_id":32,"price":1000.5,"currency":"MYR",
"products":[
{"type":"HR_ECLAIM","name":"HREClaim","is_fixed_price":true,"price":500.5,"currency":"MYR"},
{"type":"HR_ELEAVE","name":"HRELeave","is_fixed_price":true,"price":500,"currency":"MYR"}
],
"total_invoices":200,"total_staffs":80},"url":"https://drive.google.com/open?id=1Is6QsnuMLu9ZIpqeEzR2O2Ve1wUyF92aVCg55kWsOgc"}
i load [order_info][products][type] as checked products in while i load all the products from env file. I only need to save checked check box products in db.
Can someone helps me?
This is the complete working solution i done for my question!
public function edit($id, $attributes){
$orders = (new Agos())->load($id);
$json = $orders->data;
$json = json_decode($json);
$checkedit= $attributes['check_list'];
if (is_array($checkedit) || is_object($checkedit))
{
foreach($checkedit as $chked1){
$exists = false;
foreach($json->products as $key => $val)
{
// update if products exists
if($val->type == $chked1) {
$val->status = 'true';
$exists = true;
}
if(array_key_exists('status', $val)) {}
else{ $val->status = 'false';}
}
if($chked1 == 'FIN_REPORTING')
{
$name = 'Finance reporting & book keeping';
}
elseif ($chked1 == 'FIN_ADVISORY')
{
$name = 'Finance Advisory';
}
elseif ($chked1 == 'PAYROLL_HRDB')
{
$name = 'PAYROLL_HRDB';
}
elseif ($chked1 == 'HR_ELEAVE')
{
$name = 'HR E-Leave';
}
else
{
$name = 'HR E-Claim';
}
//if products not exists add new products
if(!$exists) {
$newproduct = new \stdClass();
$newproduct->type = $chked1;
$newproduct->name = $name;
$newproduct->is_fixed_price = false;
$newproduct->currency = "MYR";
$newproduct->status = "true";
array_push($json->products, $newproduct);
}
}
}
//remove all products that have status = false
foreach($json->products as $index => $product) {
if ( $product->status == "false") {
unset($json->products[$index]);
}
}
$json->products = array_values($json->products);
json_encode($json, JSON_PRETTY_PRINT);
//remove status element from products
foreach($json->products as $index => $product) {
unset($product->status);
}
$json->products = array_values($json->products);
json_encode($json, JSON_PRETTY_PRINT);
$json->google_drive_url= $attributes['data'];
$json->remark= $attributes['remark'];
$json->status= $attributes['status'];
$json->total_invoices= $attributes['total_invoices'];
$json->total_staffs= $attributes['total_staffs'];
$json1 = json_encode($json);
$status = $attributes['status'];
$total_price = str_replace(',','', $attributes['total_price']);
DB::table('orders')
->where('id', $id)
->update(['data' => $json1,'status' => $status, 'price' => $total_price]);
}

How to update a variable outside a function using a function which takes inputs and conditions the output for the variable. I am using PHP

I am making an semi-automatic attendance register so that whenever a person submits his or her name a table will get updated and change their status.
Here is the code for the form which I made:
<form action="Attendance.php" method="post">
<input type="text" name="name" placeholder="Name of
Employee" style="width: 210px;"><br>
<input type="number" name="refNo" placeholder="Reference
Number of Employee" style="width: 210px;" disabled="disabled"><br>
<input type="submit" name="submit" value="Submit"><br>
</form>
Here is the code I wrote which is a function. This function checks if the person present or not and change a variable that imports its value from the form I mentioned above:
<?php
function check_attendance($eNAME, $NAME, $eNUM){
if ($eNAME == $NAME) {
$eNUM = 'Present';
}
else{
$eNUM = 'Absent';
}
}
$eNAME = $_POST['name'];
//$eNAME is the name of the employee given in form I wrote above.
$eNUM1 = '';
//$eNUM1 is the status of the employee that is whether an employee is present or absent.
check_attendance($eNAME, 'John D', $eNUM1);
echo $eNUM1;
?>
I have yet not written the code to integrate the person being present or absent into a table.
I cannot get to update $eNUM1 using function check_attendance.
There are two ways of achieving this, the first using virtually the same code as you have is to pass the variable by reference...
function check_attendance($eNAME, $NAME, &$eNUM){
this allows the function to alter the value in the calling scope.
BUT
As you want to just set a value from the function, it would be better(IMHO) to just return the value...
function check_attendance($eNAME, $NAME){
if ($eNAME == $NAME) {
$eNUM = 'Present';
}
else{
$eNUM = 'Absent';
}
return $eNUM;
}
$eNAME = $_POST['name'];
//$eNAME is the name of the employee given in form I wrote above.
//$eNUM1 is the status of the employee that is whether an employee is present or absent.
$eNUM1 = check_attendance($eNAME, 'John D' );
echo $eNUM1;
You need to return $eNum
<?php
function check_attendance($eNAME, $NAME, $eNUM){
if ($eNAME == $NAME) {
$eNUM = 'Present';
} else{
$eNUM = 'Absent';
}
return $eNUM;
}
$eNAME = $_POST['name'];
//$eNAME is the name of the employee given in form I wrote above.
$eNUM1 = '';
//$eNUM1 is the status of the employee that is whether an employee is present or absent.
$eNUM1 = check_attendance($eNAME, 'John D', $eNUM1);
echo $eNUM1;
?>

Issue with adding to cart with json and php

I am trying to make a simple shop cart and add products from my modal to it by submitting the values with onclick add to cart function
Inside my details modal I have a form with option value attributes
<form action="add_cart.php" method="post" id="add_product_form">
<input type="hidden" name ="product_id" value ="<?=$id;?>">
<input type="hidden" name="available" id="available" value ="">
<div class="form-group">
<div class="large-3 columns">
<label for="quantity">Quantity:</label>
<input type="number" class="form-control" id="quantity" name="quantity">
</div>
</div>
<div class="large-3 columns">
<label for="size">Size:</label>
<select name="size" id="size" class="form-control">
<option value=""></option>
<?php foreach($size_array as $string) {
$string_array = explode(':', $string);
$size = $string_array[0];
$available = $string_array[1];
echo '<option value="'.$size.'" data‐available="'.$available.'">'.$size.' ('.$available.'Available)</option>';
}?>
I send the user inputs from my modal with Ajax Function add_to_cart with method post to do the processing, ajax redirects me back to products page.
I get "was added to card" from add_cart.php
code line:
$_SESSION['success_launch'] = $product['title']. 'was added to your cart.';
But only empty strings inserted inside my database table cart
Inside my developer tools in browser I am getting Notice: Undefined index: product_id in add_cart.php on line 6 , also size ,available and quantity are also undefined. I can't find the solution to it.
This is what I tried in add_cart.php :
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/konfiguracija.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/config.php';
$product_id = sanitize($_POST['product_id']);
$size = sanitize($_POST['size']);
$available = sanitize($_POST['available']);
$quantity = sanitize($_POST['quantity']);
$item = array();
$item[] = array (
'id' => $product_id,
'size' => $size,
'quantity' => $quantity,
);
$domain = ($_SERVER['HTTP_HOST'] != 'localhost')?'.'.$_SERVER['HTTP_HOST']:false;
$query = $veza->prepare("SELECT * FROM products WHERE id = '{$product_id}'");
$query ->execute();
$product = $query->fetch(PDO::FETCH_ASSOC);
$_SESSION['success_launch'] = $product['title']. 'was added to your cart.';
//check does cookie cart exist
if($cart_id != ''){
$cartQ= $veza->prepare("SELECT * FROM cart WHERE id = '{$cart_id}'");
$cart = $cartQ->fetch(PDO::FETCH_ASSOC);
$previous_items = json_decode($cart['items'],true);
$item_match = 0;
$new_items = array();
foreach ($prevous_items as $pitem){
if($item[0]['id']==$pitem['id'] && $item[0]['size'] == $pitem['size']){
$pitem ['quantity']= $pitem['quantity']+$item[0]['quantity'];
if ($pitem['quantity']>$available){
$pitem['quantity'] = $available;
}
$item_match = 1;
}
$new_items[] = $pitem;
}
if($item_match != 1){
$new_items = array_merge($item,$previous_items);
}
$items_json = json_encode($new_items);
$cart_expire = date("Y-m-d H:i:s", strtotime("+30 days"));
$something=$veza->prepare("UPDATE cart SET items = '{$items_json}',expire_date= '{$cart_expire}'WHERE id ='{$cart_id}'");
$something ->execute();
setcookie(CART_COOKIE,'',1,'/',$domain,false);
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}else {
//add cart inside database
$items_json = json_encode($item);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$smth=$veza->prepare("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}')");
$smth->execute();
$cart_id = $veza>lastInsertId();
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}
?>
That warning message means that there was an attempt to access keys in an array that do not exist.
To see the content of the $_POST array, try to do:
<?php
var_dump($_POST);
If it's empty, most probably you're using the wrong form method or the wrong HTTP method. Try this:
<?php
var_dump($_GET);
You may also debug HTTP messages using the browser development tools or something like Insomnia.
Anyway, always check if the keys exist before trying to use them:
<?php
$requiredKeys = ['product_id', 'size', 'available', 'quantity'];
foreach ($requiredKeys as $key) {
if (!isset($_POST[$key])) {
// handle error here
}
}
ADDED:
Make this change:
<?php
$requiredKeys = ['product_id', 'size', 'available', 'quantity'];
foreach ($requiredKeys as $key) {
if (!isset($_POST[$key])) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(
[
'errorMsg' => "Missing key: $key",
'missingKey' => $key,
'receivedPost' => $_POST,
]
);
die();
}
}
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/konfiguracija.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/config.php';
$product_id = sanitize($_POST['product_id']);
// The rest of the code
Keep the added validation code. Never assume $_POST is not empty.
I also noticed there's something wrong here:
var data = jQuery('add_product_from').serialize();
It should have been something like this:
var data = jQuery('#add_product_from').serialize();
Notice that I added the "#". You were sending an empty POST data.
I believe it's better to put the attribute "id" in all the "input" fields, fetch each of their values, check that was done successfully and use the values to build an object that could be used by the jQuery.ajax function. If you have done that, validating everything, most probably you would have easily noticed the mistake.
ADDED
Also, if you read the jQuery.ajax documentation, you'll notice that the success function can have parameters. Add at least the first one in order to receive the response data. Use it to check if there's an unexpected response and debug.

Search a values in Database and get all values in this single row using Codeigniter

i want to search coupon number in a row if coupon number is match given by user get all values in this single row using Codeigniter.
Here is My Code.
Model
public function ven_coupon($coupon)
{
$where = array(
'number' => $coupon,
);
$this->db->select()
->from('vendor_coupons')
->where($where);
$data = $this->db->get();
return $data->result_array();
}
Controller
public function ven_coupon()
{
$this->load->model('front');
if ($_POST) {
$number = $_POST['coupon'];
if (!$this->front->ven_coupon($number)) {
echo "Not Valid";
}
$payment = $this->cart->total();
$discount['discount'] = ($payment*10)/100;
$this->load->view('checkout',$discount);
}
}
View
<form action="<?=base_url();?>home/ven_coupon" method="post">
Coupon Number: <input type="text" name="coupon">
<input type="submit" name="submit" value="Apply Coupon">
</form>
You question is not clear what actually you need. But if you want all values from database than you need to modify your controller as:
$data = $this->front->ven_coupon($number);
if(count($data) <= 0){
echo "not valid"; // print error
}
else{
print_r($data); // print all data
}
This is basic example you can store them into variable and pass into load view.

Multidimensional array in php SESSION

I am having problem with updating an array element with in $_SESSION variable of PHP. This is the basic structure:
$product = array();
$product['id'] = $id;
$product['type'] = $type;
$product['quantity'] = $quantity;
And then by using array_push() function I insert that product in SESSION variable.
array_push($_SESSION['cart'], $product);
Now this is the main part where i m facing problem:
foreach($_SESSION['cart'] as $product){
if($id == $product['id']){
$quantity = $product['quantity'];
$quantity += 1;
$product['quantity'] = $quantity;
}
}
I want to increment product quantity within $_SESSION['cart'] variable. How can I do that?
Don't blindly stuff the product into your session. Use the product's ID as the key, then it's trivial to find/manipulate that item in the cart:
$_SESSION['cart'] = array();
$_SESSION['cart'][$id] = array('type' => 'foo', 'quantity' => 42);
$_SESSION['cart'][$id]['quantity']++; // another of this item to the cart
unset($_SESSION['cart'][$id]); //remove the item from the cart
this not best answers for u...but hope can help u guys
im not expert coders, and just learn coding in this forum ^,^ .You must always trying to solved.
for more example hope can help to update value quantity:
<?php
if(isset($_POST['test'])) {
$id =$_POST['id'];
$newitem = array(
'idproduk' => $id,
'nm_produk' => 'hoodie',
'img_produk' => 'images/produk/hodie.jpg',
'harga_produk' => '20',
'qty' => '2'
);
//if not empty
if(!empty($_SESSION['cart']))
{
//and if session cart same
if(isset($_SESSION['cart'][$id]) == $id) {
$_SESSION['cart'][$id]['qty']++;
} else {
//if not same put new storing
$_SESSION['cart'][$id] = $newitem;
}
} else {
$_SESSION['cart'] = array();
$_SESSION['cart'][$id] = $newitem;
}
}
?>
<form method="post">
<input type="text" name="id" value="1">
<input type="submit" name="test" value="test">
<input type="submit" name="unset" value="unset">
</form>
I faced the same issue before, and the accepted answer works only because it modifies the session variable directly, but in a foreach loop, you must pass the $product variable by reference (by prepending & to it) to be able to save changes like this :
foreach($_SESSION['cart'] as &$product){
if($id == $product['id']){
$product['quantity'] += 1;
}
}
Or if you follow the accepted solution :
foreach($_SESSION['cart'] as $id => &$product){
if($searchId == $id){
$product['quantity'] += 1;
}
}

Categories