public function getShoppingCartAbandonmentinfo($params){
$final_array=array();
require_once(DIR_WS_MODEL . "UserMaster.php");
require_once(DIR_WS_MODEL . 'OrderExportMaster.php');
require_once(DIR_WS_MODEL . 'BasketMaster.php');
require_once (DIR_WS_MODEL . "/ProductsMaster.php");
require_once (DIR_WS_MODEL . "/ProductPriceMaster.php");
$objProductsMaster = new ProductsMaster();
$objProductPriceMaster = new ProductPriceMaster();
$ObjUserMaster = new UserMaster();
$UserData = new UserData();
$ObjBasketMaster = new BasketMaster();
$ObjBasketData = new BasketData();
$ObjOrderExportMaster = new OrderExportMaster();
$ObjOrderExportData = new OrderExportData();
define_const(PRODUCT_SEPARATOR, '||');
$static_cust_array = array('firstname' => 'user_master.firstname AS first_name','lastname' => 'user_master.lastname AS last_name','companyname' => 'user_master.companyname AS company_name','email' => 'user_master.email','user_id' => 'user_master.userid','customer_type'=>'user_master.customer_type AS guest_customer');
$ObjBasketMaster->setSelect("user_master.userid")->setSelect((array)$static_cust_array);
$ObjBasketMaster->setJoin("LEFT JOIN user_master ON user_master.userid=user_basket.user_id");
$customer_details = $ObjBasketMaster->getBasket();
foreach ($customer_details as $customer_field_value){
$output='';
foreach ($customer_field_value as $field_key => $customer_details_value){
if($field_key == 'guest_customer' ){
$field_key ="guest_user";
if($customer_details_value == 1){
$customer_details_value = "NO";
}else{
$customer_details_value = "YES";
}
}
$output[$field_key]= $customer_details_value;
$all['customer_details']=$output;
}
$output1[]= $all;
}
//echo "<pre>";print_r($output1);echo "</pre>";exit;
/*Shopping Cart Loop */
$static_basket_array=array('basket_id'=>'user_basket.basket_id','user_basket.date'=>'date AS created_date','cart_detail'=>'user_basket.cart_detail AS products');
$ObjBasketMaster->setSelect((array)$static_basket_array);
$ObjBasketMaster->setSelect('user_basket.date AS abandoned_days');
$ObjBasketMaster->setJoin("LEFT JOIN user_master ON user_master.userid=user_basket.user_id");
$cart_details = $ObjBasketMaster->getBasket();
foreach ($cart_details as $cart_field_value){
$output='';
foreach ($cart_field_value as $field_key => $cart_details_value){
if($field_key == 'abandoned_days' ){
$OldDate = $cart_details_value;
$now = time(); // or your date as well
$your_date = strtotime($OldDate);
$datediff = $now - $your_date;
$cart_details_value=round($datediff / (60 * 60 * 24));
}
if($field_key == 'products' && !empty($cart_details_value) ){
$cart_data=unserialize($cart_details_value);
foreach ($cart_data as $key => $data){
$objProductsMaster->setSelect('products_title');
$objProductsMaster->setWhere("AND products_id = :products_id",$data['product_id'],'int');
$objProductsMaster->setWhere('AND site_language_id = :site_language_id', SITE_LANGUAGE_ID, 'int');
$datad = $objProductsMaster->getProductsDesc();
$products= array('product_id'=>$data['product_id'],'product_title'=>$datad[0]['products_title']);
}
$cart_details_value=array();
$cart_details_value= $products;
}
$output[$field_key]= $cart_details_value;
$all['shopping_cart']=$output;
}
echo "<pre>";print_r($output1);echo "</pre>";exit;
$output1[]= $all;
}
/*End OF Shopping Cart */
if(empty($output1))
$output=array('Message'=>NO_RECORD_FOUND);
return $output1;
}
}
Here in $output1 i always get the latest data, but i want all the data . The data is been over written in $output1 .
So how can i add $customer_details_value as well as $cart_details_value both in $output1.
Here after adding $cart_details_value in $output it over rides value of $customer_details_value in $output1
You need to define your $output1 before the loops:
$output1 = [];
And better start using informative variable names, to easy read the code and find the errors.
Related
I have the following code that is overwriting my array on the second pass through of the while loop.
Here is my code:
<?php
require '../vendor/autoload.php';
require_once 'constants/constants.php';
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
require('includes/application_top.php');
define("AUTHORIZENET_LOG_FILE", "phplog");
function getUnsettledTransactionList()
{
//get orders that are in the exp status
$orders_pending_query = tep_db_query("select orders_id as invoice_number from " . TABLE_ORDERS . " where orders_status = '14' order by invoice_number");
$orders_pending = array();
while ($row = mysqli_fetch_array($orders_pending_query, MYSQLI_ASSOC)) {
$orders_pending[] = $row;
}
/* Create a merchantAuthenticationType object with authentication details
retrieved from the constants file */
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName(\SampleCodeConstants::MERCHANT_LOGIN_ID);
$merchantAuthentication->setTransactionKey(\SampleCodeConstants::MERCHANT_TRANSACTION_KEY);
// Set the transaction's refId
$refId = 'ref' . time();
$pagenum = 1;
do {
$request = new AnetAPI\GetUnsettledTransactionListRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$paging = new AnetAPI\PagingType;
$paging->setLimit("1000");
$paging->setOffset($pagenum);
$request->setPaging($paging);
$controller = new AnetController\GetUnsettledTransactionListController($request);
$response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::PRODUCTION);
$transactionArray = array();
$resulttrans = array();
if (($response != null) && ($response->getMessages()->getResultCode() == "Ok")) {
if (null != $response->getTransactions()) {
foreach ($response->getTransactions() as $tx) {
$transactionArray[] = array(
'transaction_id' => $tx->getTransId(),
'invoice_number' => $tx->getInvoiceNumber()
);
// echo "TransactionID: " . $tx->getTransId() . "order ID:" . $tx->getInvoiceNumber() . "Amount:" . $tx->getSettleAmount() . "<br/>";
}
$invoiceNumbers = array_column($orders_pending, "invoice_number");
$result = array_filter($transactionArray, function ($x) use ($invoiceNumbers) {
return in_array($x["invoice_number"], $invoiceNumbers);
});
$resulttrans = array_column($result, "transaction_id");
} else {
echo "No unsettled transactions for the merchant." . "\n";
}
} else {
echo "ERROR : Invalid response\n";
$errorMessages = $response->getMessages()->getMessage();
echo "Response : " . $errorMessages[0]->getCode() . " " . $errorMessages[0]->getText() . "\n";
}
$numResults = (int) $response->getTotalNumInResultSet();
$pagenum++;
print_r($resulttrans);
} while ($numResults === 1000);
return $resulttrans;
}
getUnsettledTransactionList();
?>
the print_r($resulttrans); is actually printing 2 separate arrays, instead of my desired 1 array.
If I move the print_r($resulttrans) to after the while loop, I am only seeing the second array, meaning the first array was overwritten. I am not seeing where this is happening though as to me it seems like all results should be added onto the array.
Your code is supposed to work as you described because you are reassigning the array variable in your loop like this
$resulttrans = array_column($result, "transaction_id");
If you need to get all the resulting values in the same array you need to append it to the array. you can do that by merging the new result into your array variable like this
$resulttrans = array_merge($resulttrans, array_column($result, "transaction_id"));
I am getting error after saving sales and error is occurring in update product function, this function is working fine when i am updating product, but when i try to update product using edit-sales it is giving me this error.
Error
Code where error is
Picture 1 is what error i am getting after saving the edited sales..
picture 2 is code where error is occurring....
This is controller.sales ( which is calling model.edit-sales)
static public function ctrEditSale(){
if(isset($_POST["editSale"])){
/*=============================================
FORMAT PRODUCTS AND CUSTOMERS TABLES
=============================================*/
$table = "sales";
$item = "code";
$value = $_POST["editSale"];
$getSale = ModelSales::mdlShowSales($table, $item, $value);
/*=============================================
CHECK IF THERE'S ANY EDITED SALE
=============================================*/
if($_POST["productsList"] == ""){
$productsList = $getSale["products"];
$productChange = false;
}else{
$productsList = $_POST["productsList"];
$productChange = true;
}
if($productChange){
$products = json_decode($getSale["products"], true);
$totalPurchasedProducts = array();
foreach ($products as $key => $value) {
array_push($totalPurchasedProducts, $value["quantity"]);
$tableProducts = "products";
$item = "id";
$value1 = $value["id"];
$order = "id";
$getProduct = ProductsModel::mdlShowProducts($tableProducts, $item, $value1, $order);
$item1a = "sales";
$value1a = $getProduct["sales"] - $value["quantity"];
$newSales = ProductsModel::mdlUpdateProduct($tableProducts, $item1a, $value1a, $value);
$item1b = "stock";
$value1b = $value["quantity"] + $getProduct["stock"];
$stockNew = ProductsModel::mdlUpdateProduct($tableProducts, $item1b, $value1b, $value);
}
$tableCustomers = "customers";
$itemCustomer = "id";
$valueCustomer = $_POST["selectCustomer"];
$getCustomer = ModelCustomers::mdlShowCustomers($tableCustomers, $itemCustomer, $valueCustomer);
$item1a = "purchases";
$value1a = $getCustomer["purchases"] - array_sum($totalPurchasedProducts);
$customerPurchases = ModelCustomers::mdlUpdateCustomer($tableCustomers, $item1a, $value1a, $valueCustomer);
/*=============================================
UPDATE THE CUSTOMER'S PURCHASES AND REDUCE THE STOCK AND INCREMENT PRODUCT SALES
=============================================*/
$productsList_2 = json_decode($productsList, true);
$totalPurchasedProducts_2 = array();
foreach ($productsList_2 as $key => $value) {
array_push($totalPurchasedProducts_2, $value["quantity"]);
$tableProducts_2 = "products";
$item_2 = "id";
$value_2 = $value["id"];
$order = "id";
$getProduct_2 = ProductsModel::mdlShowProducts($tableProducts_2, $item_2, $value_2, $order);
$item1a_2 = "sales";
$value1a_2 = $value["quantity"] + $getProduct_2["sales"];
$newSales_2 = ProductsModel::mdlUpdateProduct($tableProducts_2, $item1a_2, $value1a_2, $value_2);
$item1b_2 = "stock";
$value1b_2 = $getProduct_2["stock"] - $value["quantity"];
$newStock_2 = ProductsModel::mdlUpdateProduct($tableProducts_2, $item1b_2, $value1b_2, $value_2);
}
$tableCustomers_2 = "customers";
$item_2 = "id";
$value_2 = $_POST["selectCustomer"];
$getCustomer_2 = ModelCustomers::mdlShowCustomers($tableCustomers_2, $item_2, $value_2);
$item1a_2 = "purchases";
$value1a_2 = array_sum($totalPurchasedProducts_2) + $getCustomer_2["purchases"];
$customerPurchases_2 = ModelCustomers::mdlUpdateCustomer($tableCustomers_2, $item1a_2, $value1a_2, $value_2);
$item1b_2 = "lastPurchase";
date_default_timezone_set('America/Bogota');
$date = date('Y-m-d');
$hour = date('H:i:s');
$value1b_2 = $date.' '.$hour;
$dateCustomer_2 = ModelCustomers::mdlUpdateCustomer($tableCustomers_2, $item1b_2, $value1b_2, $value_2);
}
/*=============================================
SAVE PURCHASE CHANGES
=============================================*/
$data = array("idSeller"=>$_POST["idSeller"],
"idCustomer"=>$_POST["selectCustomer"],
"code"=>$_POST["editSale"],
"products"=>$productsList,
"tax"=>$_POST["newTaxPrice"],
"netPrice"=>$_POST["newNetPrice"],
"totalPrice"=>$_POST["saleTotal"],
"paymentMethod"=>$_POST["listPaymentMethod"]);
$answer = ModelSales::mdleditSale($table, $data);
if($answer == "ok"){
echo'<script>
localStorage.removeItem("range");
swal({
type: "success",
title: "The sale has been edited correctly",
showConfirmButton: true,
confirmButtonText: "Close"
}).then((result) => {
if (result.value) {
window.location = "sales";
}
})
</script>';
}
}
}
above code is calling model edit-sales with data to update database
This is model edit sales method
mdl:editsale
you put in last attribute all array $value, you only need to put only id $value['id']
$item1a = "sales";
$value1a = $getProduct["sales"] - $value["quantity"];
$newSales = ProductsModel::mdlUpdateProduct($tableProducts, $item1a, $value1a, $value['id']);
$item1b = "stock";
$value1b = $value["quantity"] + $getProduct["stock"];
$stockNew = ProductsModel::mdlUpdateProduct($tableProducts, $item1b, $value1b, $value['id']);
I'm running through some distinct user ID's (about 147 of them, retrieved from a table with many duplicates) with a foreach loop and then when retrieved, using them to retrieve more user details. I then place these details within an array in order to push them to my JavaScript.
For some reason the result that I get from the array is what seems to be an infinite loop that has quit somewhere in the process.
Here's an example:
This is the code that I am currently running:
public function payments_rt_search() {
global $wpdb;
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$threshold = intval($_POST['threshold']);
$results = $wpdb->get_results( "SELECT DISTINCT vendor_id FROM {$wpdb->prefix}wcpv_commissions WHERE order_date BETWEEN '".$date1."' AND '".$date2."'");
$past_threshold_users = [];
// echo json_encode($results);
// wp_die();
foreach ($results as $user_R) {
$total_commissions = $wpdb->get_results( "SELECT SUM(product_commission_amount) AS TotalCommissions FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id);
$total_commission = 0;
foreach($total_commissions as $total_commission_res)
{
$total_commission = $total_commission_res->TotalCommissions;
}
if ($total_commission >= $threshold)
{
$res2 = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id." LIMIT 1");
// echo json_encode($res2[0]);
// wp_die();
//Add user details to array
$user_deets = $res2[0];
$user_arr = array(
'vendor_id' => $user_deets->vendor_id,
'vendor_name' => $user_deets->vendor_name,
'paypal_email' => '',
'amount' => $total_commission,
'currency' => '$',
'commission_status' => $user_deets->commission_status
);
$past_threshold_users[] = $user_arr;
// echo json_encode($user_arr);
// wp_die();
}
else
{
continue;
}
echo json_encode($past_threshold_users);
}
//echo json_encode($results);
wp_die();
}
Try this code
I have move this echo json_encode($past_threshold_users); code after foreach loop.
public function payments_rt_search() {
global $wpdb;
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$threshold = intval($_POST['threshold']);
$results = $wpdb->get_results( "SELECT DISTINCT vendor_id FROM {$wpdb->prefix}wcpv_commissions WHERE order_date BETWEEN '".$date1."' AND '".$date2."'");
$past_threshold_users = [];
// echo json_encode($results);
// wp_die();
foreach ($results as $user_R) {
$total_commissions = $wpdb->get_results( "SELECT SUM(product_commission_amount) AS TotalCommissions FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id);
$total_commission = 0;
foreach($total_commissions as $total_commission_res)
{
$total_commission = $total_commission_res->TotalCommissions;
}
if ($total_commission >= $threshold)
{
$res2 = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id." LIMIT 1");
// echo json_encode($res2[0]);
// wp_die();
//Add user details to array
$user_deets = $res2[0];
$user_arr = array(
'vendor_id' => $user_deets->vendor_id,
'vendor_name' => $user_deets->vendor_name,
'paypal_email' => '',
'amount' => $total_commission,
'currency' => '$',
'commission_status' => $user_deets->commission_status
);
$past_threshold_users[] = $user_arr;
// echo json_encode($user_arr);
// wp_die();
}
/*else
{
continue;
} */
}
echo json_encode($past_threshold_users);
//echo json_encode($results);
wp_die();
}
I am trying to get more than 1 item in my shopping cart array but I run into an issue
This is my database after inserting 1 item with post method
Items is defined in db as text
After trying to insert second product the items result gets overwritten.
My developers tools output after clicking add to cart
ADD
I am using add to cart button from my modal >https://pastebin.com/HKSRTG4L that is submitting via ajax and parsed to add-cart.php
Where I have add to cart function : https://pastebin.com/guv0rB6x
This is my code from cart.php :
<?php
include_once $_SERVER['DOCUMENT_ROOT']."/EcomApp/konfiguracija.php";
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/config.php';
include 'include/head.php';
include 'include/izbornik.php';
if($cart_id != ''){
$cartQ = $veza->prepare("SELECT * FROM cart WHERE id = '$cart_id';");
$cartQ->execute();
$result= $cartQ->fetch(PDO::FETCH_ASSOC);
$items = json_decode($result['items'],true);var_dump($items) ;
$i = 1;
$sub_total = 0;
$item_count = 0;
}
?>
<div class="col-md-12">
<div class="row">
<h2 class ="text-center">Your Shopping Cart </h2><hr>
<?php if($cart_id =='') :?>
<div class="bg-danger">
<p class="text-center text-danger">
Your shopping cart is empty!
</p>
</div>
<?php else: ?>
<table class="table" >
<thead><th>#</th><th>Item</th><th>Price</th><th>Quantity</th><th>Size</th><th>Sub Total</th></thead>
<tbody>
<?php
foreach ($items as $item){
$product_id =$item['id'];
$productQ = $veza ->prepare("SELECT * FROM products WHERE id = '$product_id'");
$productQ ->execute();
$product= $productQ->fetch(PDO::FETCH_ASSOC);
$sArray = explode (',',$product['sizes']);
foreach($sArray as $sizeString){
$s = explode(':',$sizeString);
if($s[0] ==$item['size']){
$available = $s[1];
}
}
?>
<tr>
<td><?=$i;?></td>
<td><?=$product['title'];?></td>
<td><?=$product['price'];?></td>
<td><?=$item['quantity'];?></td>
<td><?=$item['size'];?></td>
<td><?=$item['quantity'] * $product['price'];?></td>
</t>
<?php } ?>
</tbody>
</table>
<?php endif; ?>
</div>
<?php include 'include/footer.php';?>
I am 93% sure the problem is with array merge since currently the insert is overwriting the row with new results and not adding to the array.
<?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,(array)$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 {
INSERT
//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);
}
var_dump($cart_id);
?>
add to cart function : https://pastebin.com/guv0rB6x
function add_to_cart(){
jQuery('#modal_errors').html("");
var size = jQuery('#size').val();
var quantity = jQuery('#quantity').val();
var available = jQuery('#available').val();
var error = '';
var data = jQuery("#add_product_form").serialize();
if(size == '' || quantity == '' || quantity == 0){
error += '<p class= "bg-danger text-center">You must choose a size and quantity</p>';
jQuery('#modal_errors').html(error);
return;
}else if (quantity>available){
error += '<p class= "bg-danger text-center">There are only '+available+' available.</p>';
jQuery('#modal_errors').html(error);
return;
}else{
jQuery.ajax({
url: '/EcomApp/admin/parsers/add_cart.php',
method : 'post',
data : data,
success : function(){
location.reload();
},
error : function(){alert("Something went wrong");}
});
}
}
konfiguracija.php there is a (Undefined offset: 1) on line 65
$user_data['last'] = $fn1;
but I think it is not directly connected to the functionality
try{
$veza = new PDO("mysql:host=" . $host . ";dbname=" . $dbname,$dbuser,$dbpass);
$veza->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$veza->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8';");
$veza->exec("SET NAMES 'utf8';");
}catch(PDOException $e){
switch($e->getCode()){
case 1049:
header("location: " . $eone . "error/wrongDBname.html");
exit;
break;
default:
header("location: " . $eone . "error/error.php?code=" . $e->getCode());
exit;
break;
}
}
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/config.php';
require_once BASEURL.'helpers/helpers.php';
session_start();
//
$cart_id = '';
if(isset($_COOKIE[CART_COOKIE])){
$cart_id = sanitize($_COOKIE[CART_COOKIE]);
}
if(isset($_SESSION['SDUser'])){
$user_id =$_SESSION['SDUser'];
$query = $veza->prepare("SELECT* FROM korisnik WHERE id ='$user_id'");
$query->execute();
$user_data = $query->fetch(PDO::FETCH_ASSOC);
$fn = explode(' ', $user_data['full_name']);
$user_data['first'] = $fn[0];
$user_data['last'] = $fn[1];
// print_r($user_data);
}
if(isset($_SESSION['success_launch'])){
echo '<h1><p class="text-success">'.$_SESSION['success_launch'].'</p></h1>';
unset($_SESSION['success_launch']);
}
if(isset($_SESSION['error_launch'])){
echo '<div class="success"><p class="text-success">'.$_SESSION['error_launch'].'</p></div>';
unset($_SESSION['error_launch']);
}
In add_cart.php:
$previous_items = json_decode($cart['items'],true);
$item_match = 0;
$new_items = array();
foreach ($prevous_items as $pitem){
Notice that $previous_items and $prevous_items are different.
That's why you're getting:
Notice: Undefined variable: prevous_items in
/opt/lampp/htdocs/EcomApp/admin/parsers/add_cart.php on line 29
You didn't take my previous advice to make your life easier.
Apparently working code is not enough. Always validate and fail fast ( http://www.practical-programming.org/ppl/docs/articles/fail_fast_principle/fail_fast_principle.html ):
if(!$cart_id){
$cartQ = $veza->prepare("SELECT * FROM cart WHERE id = ?");
$cartQ->execute([(int)$cart_id]);
$result= $cartQ->fetch(PDO::FETCH_ASSOC);
if (!isset($result['items'])) {
throw new \RuntimeException("The items were not found.");
}
$items = json_decode($result['items'],true);
if (!$items) {
throw new \RuntimeException("Invalid items format.");
}
$i = 1;
$sub_total = 0;
$item_count = 0;
}
As said, do something like this:
<?php
$validKeys = ['product_id', 'size', 'available', 'quantity'];
foreach ($validKeys as $key) {
if (!isset($_POST[$key])) {
throw new RuntimeException("Parameter $key is missing.");
}
}
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']);
Most probably you missed something in the client side (javascript or HTML form), for instance, you might have misspelled "product_id".
ADDED:
https://pastebin.com/guv0rB6x
function add_to_cart(){
jQuery('#modal_errors').html("");
var size = jQuery('#size').val();
var quantity = jQuery('#quantity').val();
var available = jQuery('#available').val();
var error = '';
var data = jQuery("#add_product_form").serialize();
if(size == '' || quantity == '' || quantity == 0){
error += '<p class= "bg-danger text-center">You must choose a size and quantity</p>';
jQuery('#modal_errors').html(error);
return;
}else if (quantity>available){
error += '<p class= "bg-danger text-center">There are only '+available+' available.</p>';
jQuery('#modal_errors').html(error);
return;
}else{
jQuery.ajax({
url: '/EcomApp/admin/parsers/add_cart.php',
method : 'post',
data : data,
success : function(){
location.reload();
},
error : function(){alert("Something went wrong");}
});
}
}
You're not checking if the "product_id" field is empty.
ADDED:
Replace:
$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,(array)$previous_items);
}
With something like this:
$previous_items = json_decode($cart['items'], true);
if (!$previous_items) {
$previous_items = array();
}
$items_by_unique = array();
foreach (array_merge($item, $previous_items) as $item) {
if (!isset($item['id'], $item['size'], $item['quantity'])) {
throw new RuntimeException('Found a invalid invalid data: ' . json_encode($item));
}
$unique = $item['id'] . '-' . $item['size'];
if (isset($items_by_unique[$unique])) {
$old_item = $items_by_unique[$unique];
$item['quantity'] = $old_item['quantity'];
}
if ($item['quantity'] > $available) {
$item['quantity'] = $available;
}
$items_by_unique[$unique] = $item;
}
$items_json = json_encode(array_values($items_by_unique));
The code has lots of issues that make very hard to find the mistakes and it's very hard to answer a question which is really several questions which are always increasing, as if we're making a debugging service for free... We could be discussing here for several hours and days, like a job, until everything is corrected. In that case, it's going to be very hard to help and take care of our personal lives and jobs.
Anyway, I'm going to enumerate some issues that make the code very hard to debug.
Most of the returned values are not validated, assuming that they're what's expected, instead failing immediately when there's an error. That means that you may only notice there's a mistake a lot later and hunt for the its source, which might be in a different file.
For instance, when you do something like this:
$query = $veza->prepare("SELECT * FROM products WHERE id = '$product_id'");
$query->execute();
$product = $query->fetch(PDO::FETCH_ASSOC);
You should always check if $product is at least not empty:
if (!$product) {
throw new RuntimeException("The product #$product_id" was not found.");
}
Also, putting variables inside SQL statements can be very dangerous. If you're using prepared statements you should do something like this:
$query = $veza->prepare("SELECT * FROM products WHERE id = ? LIMIT 1");
$query->execute([$product_id]);
The code does not take advantage of reusability. You can implement classes or functions and test them independently.
For instance, you could have done something like this:
<?php
/**
* Add a new item ...
*
* If it's being requested more items then available ...
*
* #param array $newItem The new item that should be added.
* #param array $items The list of items where the item should be added.
* #param integer $available Available items.
* #return void
*/
function add_item(array $newItem, array &$items, int $available=MAX_INT_MAX)
{
throw_error_if_invalid_item($newItem);
$unique = $newItem['id'] . '-' . $newItem['size'];
if (isset($items_by_unique[$unique])) {
add_item_quantity(
$items_by_unique[$unique],
$item['quantity'],
$available
);
} else {
$items[] = $newItem;
}
}
/**
* Add quantity ...
*
* #param array $item ...
* #param integer $moreQuantity ...
* #param integer $available ...
* #return void
*/
function add_item_quantity(array &$item, int $moreQuantity, int $available=MAX_INT_MAX)
{
$item['quantity'] += $moreQuantity;
if ($item['quantity'] > $available) {
$item['quantity'] = $available;
}
}
/**
* ...
*
* #param array $item ...
* #return void
*/
function throw_error_if_invalid_item(array $item)
{
if (!isset($item['id'], $item['size'], $item['quantity'])) {
throw new RuntimeException(
'Found a invalid invalid item data: ' . json_encode($item)
);
}
}
Then you can make individual test in isolated files:
<?php
$item = array(
'id' => 10,
'size' => 'm',
'quantity' => 2,
);
add_item_quantity($item, 3, 10);
if ($item['quantity'] != 5) {
echo "wrong! quantity = {$item['quantity']}\n";
} else {
echo "correct!\n";
}
If you put your classes or functions in dedicated files, you can reuse them as a library making the code easy to read, testable and secure:
<?php
throw_error_if_invalid_item($_POST);
$newItem = create_item($_POST);
$items = fetch_cart_items($cart_id);
add_item($newItem, $items, 10);
save_cart_items($items);
show_json_items($json);
With classes it would be much easier (eg: you wouldn't have to worry about missing array keys) and you could use PHPUnit to test all the functions and methods automatically. Check how I did that for a simple project:
https://github.com/pedroac/nonce4php
You can also make any error or warning halt the script:
<?php
set_error_handler(
function (int $errno , string $errstr, string $errfile, int $errline) {
http_response_code(500);
echo "ERROR #$errono:$errfile:$errline: $errstr";
die();
}
);
set_exception_handler(
function (Throwable $exception) {
http_response_code(500);
echo $exception->getMessage();
die();
}
);
If you follow the good practices, it will be much easier to found mistakes and let others help you.
I fixed this issue by casting the second argument of array_merge to an array:
$new_items = array_merge($item, (array)$previous_items);
We are trying to fetch value from database & display related value for all rows.
but code is fetching only first row value in DB & displaying same value for all rows.
Database
Site
function getDesignerCollection()
{
$i = 0;
foreach($order as $orderData)
{
$orderitems = $orderData['dproduct_id'];
$orderitemsarray = explode(",", $orderitems);
$k = 0;
while ($k < count($orderitemsarray))
{
if($data['dpaid_status']=='P'){$dpaid_status='Paid';}
if($data['dpaid_status']=='U'){$dpaid_status='Unpaid';}
if($data['dpaid_status']=='R'){$dpaid_status='Returned';}
if($data['dpaid_status']==''){$dpaid_status='';}
if ($orderitemsarray[$k] != '0')
{
$stmtorders = $user_home->runQuery("SELECT * FROM order_details");
$stmtorders->execute(array(
":dorder_id" => $orderData['entity_id']
));
$roworders = $stmtorders->fetch(PDO::FETCH_ASSOC);
if ($roworders['dproduct_id'] == '')
{
$dorderStatus = "Unpaid";
}
else
{
$dorderStatus = $roworders['dpaid_status'];
}
$responce[] = array(
$orderData->getIncrementId() ,
$orderData->getIncrementId() ,
$orderitemsarray[$k],
$dorderStatus
);
}
$k++;
$i++;
}
}
echo json_encode($responce);
}
full code : http://pastebin.com/GnT980nL
You need use fetchAll() instead fetch()
http://php.net/manual/ru/pdostatement.fetchall.php
Your function must looks like:
function getDesignerCollection() {
global $is_admin;
$user_home = new USER();
require_once '../../app/Mage.php';
Mage::app();
$stmts = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmts->execute(array(
":uid" => $_SESSION['userSession']
));
$rows = $stmts->fetchAll(PDO::FETCH_ASSOC);
}
Now in $rows you have array of associative arrays.