I have some code that runs correctly on localhost, but shows an error message on the server:
Warning: Invalid argument supplied for foreach()
If I click on add to basket, my code first checks if it was in cookie it doesn't add id to array if it doesn't in cookie, the id of product add to end of array and cookie is set
This is my code in class :
<?php
class Cart
{
//Add a product order to our COOKIE/JSON based cart.
public function AddProduct($productid, $quantity)
{
$x=0;
//Checks to see if cart already exists.
if (isset($_COOKIE['Cart']))
{
//JSON content is turned back into array.
$cart = json_decode($_COOKIE['Cart']);
foreach ($cart as $order => $product)
{
//Check to see if $products key ($order) matches the $products key we wish to remove.
if($product[0] == $productid)
{
//If result is false add product order to new array.
$record=$order;
$x=1;
}
}
if($x==1){
}else{
$cart[] = array($productid,$quantity);
//Encode cart array back into JSON.
$createcart = json_encode($cart);
setcookie('Cart',$createcart,time()+3600);
}
}
else
{
$cart = array();
$cart[] = array($productid,$quantity);
//Encode cart array back into JSON.
$createcart = json_encode($cart);
setcookie('Cart',$createcart,time()+3600);
}
//Add product id and quantity desired to cart.
}
//Displays our Cart to the page.
public function DisplayCart()
{
if (isset($_COOKIE['Cart']))
{
$cart = $_COOKIE['Cart'];
//JSON content is turned back into array.
$products = json_decode($cart);
//Loop through Cart array to display relevant Cart info.
//print_r($products);
foreach($products as $order => $product)
{
$myarr[]=$product[0];
//echo '<p>';
//echo $order;
//echo $product[0];
//echo $product[1];
//echo '</p>';
}
return $myarr;
}
else
{
echo 'No Products In Cart';
}
}
//Remove product order from Cart.
public function RemoveProduct($orderid)
{
$cart = $_COOKIE['Cart'];
//JSON content is turned back into array.
$products = json_decode($cart);
$newcart = array();
foreach ($products as $order => $product)
{
//Check to see if $products key ($order) matches the $products key we wish to remove.
if($product[0] != $orderid)
{
//If result is false add product order to new array.
$newcart[] = array($product[0], $product[1]);
}
}
//Encode new Cart array into JSON.
$createcart = json_encode($newcart);
setcookie('Cart',$createcart,time()+3600);
}
public function CountCart()
{
if (isset($_COOKIE['Cart']))
{
$cart = $_COOKIE['Cart'];
//JSON content is turned back into array.
$products = json_decode($cart);
//count array.
$count=count($products);
return $count;
}
else
{
return '0';
}
}
}
?>
<?php
if(isset($_POST['addtobasket']) && !empty($_POST['addtobasket'])){
$id=clearxss($_POST['id']);
require_once('basket/product.cl.php');
$cart=new Cart();
$cart-> AddProduct($id,'1');
//echo "yes";
//header("Location: http://www.srgiran.com/index.php?srg=basket");
}
?>