dqwn64004 2018-04-02 05:29
浏览 96
已采纳

为购物车内的foreach()提供的参数无效,

enter image description here 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

enter image description here 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

enter image description here

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

enter image description here

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']);
}
  • 写回答

3条回答 默认 最新

  • duanjianqu3685 2018-04-02 18:30
    关注

    I fixed this issue by casting the second argument of array_merge to an array:

    $new_items = array_merge($item, (array)$previous_items);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件