I am trying to make a shopping cart in php using sessions. I am having trouble making it so when you add more than one item to the shopping cart, that it will display ALL items that are added to the cart. As of right now I have it so only one thing can be in a shopping cart and when you leave the page or add another item, the last item gets overwritten. I know I must add a session like $_SESSION['cart'] and save the information in there when it gets printed out but I am unsure how to do that. Any help would be appreciated.
$prodid=$_GET['pid'];
$quan=$_GET['quantity'];
$query="select * from Products where ProductID = '$prodid'";
$result=mysql_query($query);
$numOfRows=mysql_numrows($result);
for($i=0;$i<$numOfRows;$i++)
{
$productID=mysql_result($result, $i, "ProductID");
$prodTitle=mysql_result($result, $i, "Title");
$prodAuthor=mysql_result($result, $i, "Author1");
$prodPrice=mysql_result($result, $i, "Price");
Print"<h4>ID: $productID \n </h4>";
Print"<h4>Title: $prodTitle \n </h4>";
Print"<h4>Author: $prodAuthor \n </h4>";
Print"<h4>Price: $ $prodPrice \n </h4>";
}
EDIT:
$prodid=$_GET['pid'];
$quan=$_GET['quantity'];
Print"$prodid";
Print"<br/>";
Print"$quan";
$query="select * from Products where ProductID = '$prodid'";
$result=mysql_query($query);
$numOfRows=mysql_numrows($result);
for($i=0;$i<$numOfRows;$i++)
{
$productID=mysql_result($result, $i, "ProductID");
$prodTitle=mysql_result($result, $i, "Title");
$prodPrice=mysql_result($result, $i, "Price");
}
$arr = array(
['id'] => "$productID",
['title'] => "$prodTitle",
['count'] => "$quan",
['price'] => "$prodPrice"
);
echo "id is " . $arr['id'];
You could simply form an array with the necessary item details in it:
$arr = array(
['id'] => 123
['title'] => 'some title'
['count'] => 1
['price'] => 9.99
);
You then save that array to $_SESSION with
$_SESSION['cart'] = $arr;
When you're ready to add another item to the cart, create another array with the same keys as $arr - $newArr - and append that array to the session variable:
$_SESSION['cart'][] = $newArr;
Now, when you're ready to read all the items in the cart, you have an associative array to read from:
for($x = 0; $x < count($_SESSION['cart']); $x++) {
echo $_SESSION['cart'][$x]['title'];
}
One of the best ways for shopping cart is to use database table.
1) simply create a table cart (id, guest-id, product-id, date)
2) generate guest id and assign to session once guest is clicked add to cart
example:
if(isset($_GET['adtocart'])){
if(!isset($_SESSION['guest'])){
$ipaddress = $_SERVER['REMOTE_ADDR'];
$id = uniqid(rand());
$addnewguest = mysql_query("insert into guest values('$id', '$ipaddress', sysdate())");
if($addnewguest)
$_SESSION['guest'] = $id;
else
header('location: ../en/systemnotify.php?case=002');
}
$cartid = uniqid(rand());
$guestid = $_SESSION['guest'];
$productid = $_GET['adtocart'];
$getproduct = mysql_fetch_array(mysql_query("select * from product where id = '$productid'"));
$url = $getproduct['url'];
$title = mysql_real_escape_string($getproduct['title']);
$price = $getproduct['price'];
$image = $getproduct['image'];
$info = mysql_real_escape_string($getproduct['info']);
$cartid = uniqid(rand());
$addtocart = mysql_query("insert into cart values('$cartid', '$guestid', '$productid', '$url', '$title', '$price', '$image', '$info', sysdate()) ");
if($addtocart){
header('location: '.$_SERVER['HTTP_REFERER'].$gpath.'added');
}
else
print mysql_error();
}
Related
I'm having a problem in doing something.
I have this code snippet to add a product to cart:
$product_id = isset($_GET['product_id']) ? $_GET['product_id'] : "";
$product_name = isset($_GET['product_name']) ? $_GET['product_name'] : "";
$sql = "SELECT * FROM products WHERE product_id LIKE '{$product_id}' AND product_name LIKE '{$product_name}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
if($num == 1)
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
if(!isset($_SESSION['cart']))
{
$product_id_session = 1;
}
else
{
$count = count($_SESSION['cart']);
$product_id_session = $count++;
}
$columns = array
(
'product_id_session' => $product_id_session,
'product_id' => $product_id,
'product_name' => $product_name,
'product_price' => $product_price
);
$_SESSION['cart'][$product_id_session] = $columns;
redirect_to('products.php?&message=added&product_name='. $_SESSION['cart'][$product_id_session]['product_name']);
}
}
As you can see, if the session cart is created, I assign the variable $product_id_session with the count of SESSION arrays plus one. Otherwise, the variable $product_id_session is set to 1. In the cart page I have a link to remove the selected product:
foreach($_SESSION['cart'] as $product)
{
echo "<button onClick=\"location.href='remove.php?product_id_session={$product['product_id_session']}'\">
Remove from cart
</button>";
}
Then, in the remove.php file I have this to process the data from Query String and remove the product from the cart:
$product_id_session = isset($_GET['product_id_session']) ? $_GET['product_id_session'] : "";
unset($_SESSION['cart'][$product_id_session]);
The problem I'm facing is: for example, I added two products in the cart. Then I removed the first product and added another product to the cart. The new product, instead of being added, just will replace the product that was previously added in the cart and the $product_id_session will be always the same value. What I'm doing wrong? How to specify an ID for the SESSION?
You can add new items to the cart just with:
$_SESSION['cart'][] = $columns;
Then it will be appended to end of the array.
And, after deleting item from the array, you can (but it is not necessary) re-index it by
$_SESSION['cart'] = array_values($_SESSION['cart']);
When printing out the cart, you just update the foreach loop to catch the key value into some variable, i.e. $index. The difference is in the $index=>$product part.
foreach($_SESSION['cart'] as $index=>$product)
{
echo "<button onClick=\"location.href='remove.php?product_id_session={$index}'\">
Remove from cart
</button>";
}
Remove.php remains basically the same, I just updated it for better readibility:
if (isset($_GET['product_id_session']) and $_GET['product_id_session']) {
$product_id_session = $_GET['product_id_session'];
unset($_SESSION['cart'][$product_id_session]);
}
Instead of trying to create an extra ID to manage your cart you should just rely on the unique product ID already stored in your database :
if($num == 1) {
$row = $stmt->fetch(PDO::FETCH_ASSOC); // no need for the loop as you only have 1 result
extract($row);
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
// keep track of the added product for the time being
if (!isset($_SESSION['cart'][$product_id])) {
$columns = array(
'product_id_session' => $product_id_session,
'product_id' => $product_id,
'product_name' => $product_name,
'product_price' => $product_price,
'amount' => 0, //just add last comma as good practise here
);
$_SESSION['cart'][$product_id] = $columns;
}
//raise the amount
$_SESSION['cart'][$product_id]['amount']++;
redirect_to('products.php?&message=added&product_name='. $_SESSION['cart'][$product_id_session]['product_name']);
}
And change the remove accordingly :
foreach($_SESSION['cart'] as $product) {
echo "<button onClick=\"location.href='remove.php?product_id={$product['product_id']}'\">Remove from cart</button>";
}
EDIT :
To keep an "unique" id you should not use count to calculate the ID
Just use an extra variable to keep track of last Id :
if(!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
$_SERVER['cart_product_id'] = 1;
}
else
{
$_SERVER['cart_product_id']++;
$product_id_session = $_SERVER['cart_product_id'];
}
How would I adjust individual values within the $_SESSION array depending on whether the user is logged_in or not logged_in. So basically the array values equate to the individual item prices within the shopping cart and will be adjusted if the user logs in or logs out of the SESSION.
Here's my current code:
PHP
if(!empty($_SESSION)){
foreach($_SESSION['basket'] as $b){
if ($session->logged_in) { $b['itemprice'] = ""; }
$sub_total = $b['itemprice'] * $b['itemqty'];
$total = $total + $sub_total;
// display contents of shopping cart
}
}
elseif (empty($_SESSION)) { ?>
// display message informing the user that their cart is empty
MYSQL
$itemids = array();
foreach ($_SESSION['basket'] as $item) {
$itemids[] = "'" . $item['itemid'] . "'";
}
$itemids_str = implode(',', $itemids);
$query = mysql_query("SELECT product_id, price, price_100 FROM product WHERE product_id IN ($itemids_str)");
while ($result=mysql_fetch_array($query)) { }
The closest I've come to getting this to work is each product in the cart is given the same price which changes if the user logs in or out. However, I need each item to change to the new price specific to that items product ID.
Some of our members receive a discount on certain items, so once the user logs in from being a GUEST to the registered USER the price needs to be changed on page refresh.
An example being :
**Logged in == FALSE**
Item 1 Price: 100.00
Item 2 Price: 100.00
**User logs in (Logged in == TRUE)**
Item 1 Price: 85.00
Item 2 Price: 94.00
I hope I've been clear - any advice would be appreciated.
Thanks
OPTION A:
function updateCartPrices()
{
$itemids = array();
foreach ($_SESSION['basket'] as $item) {
$itemids[] = "'" . $item['itemid'] . "'";
}
$itemids_str = implode(',', $itemids);
$query = mysql_query("SELECT product_id, price, price_100 FROM product WHERE product_id IN ($itemids_str)");
while ($result=mysql_fetch_array($query)) {
foreach ($_SESSION['basket'] as $key => $item)
{
if($result['product_id'] == $item['itemid'])
{
$_SESSION['basket'][$key]['itemprice'] = ($_SESSION['logged_in']) ? $result['price'] : $result['price_100'];
}
}
}
}
if(!empty($_SESSION)){
updateCartPrices();
foreach($_SESSION['basket'] as $b){
$sub_total = $b['itemprice'] * $b['itemqty'];
$total = $total + $sub_total;
// display contents of shopping cart
}
}
elseif (empty($_SESSION)) { ?>
// display message informing the user that their cart is empty
OPTION B (performance better):
function getLoggedInPrices()
{
$itemids = array();
foreach ($_SESSION['basket'] as $item) {
$itemids[] = "'" . $item['itemid'] . "'";
}
$itemids_str = implode(',', $itemids);
$query = mysql_query("SELECT product_id, price, price_100 FROM product WHERE product_id IN ($itemids_str)");
$prices = array();
while ($result=mysql_fetch_array($query)) {
$prices[$result['product_id']] = $result['price'];
}
return $prices;
}
if(!empty($_SESSION)){
$loggedInPrices = getLoggedInPrices();
foreach($_SESSION['basket'] as $b){
if($_SESSION['logged_in'])
{
$b['itemprice'] = $loggedInPrices[$b['itemid']];
}
$sub_total = $b['itemprice'] * $b['itemqty'];
$total = $total + $sub_total;
// display contents of shopping cart
}
}
elseif (empty($_SESSION)) {
I have a product table from where I am checking that quantity for respective product id(s) is valid or not..
this is the code snippet :
$pids = explode(',',$pid); /*in the form of 2,3,4.....*/ /*$pid->product_id*/
$q = explode(',',$q_total); /*in the form of 2,3,4.....*/ /*$q->quantity*/
/*checking start*/
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
if($quants > $quantity_rem){
$array = array();
$array['errquant'] = 'wrong_quant';
$array['error_pr'] = $ps;
echo json_encode($array);
exit; /*stop the rest of the code from executing*/
}
}
/*rest of the code outside the loop*/
So here what is happening is it checks the quantity ($quantity_rem) from table of a product id and if that quantity is less than the quantity given ($q), then the script stops and echo the product id..
But I have more that 1 product .. It's not checking the rest since whenever there is a fault it stops and echo out. I want to check all the products and echo out the product id(s) and stop the rest of the script outside the loop..
Help needed!
Thanks.
and please don't talk to me about sql injection because i know it is vulnerable and i will take care of that..
Try this:
$pids = explode(',',$pid); /*in the form of 2,3,4.....*/ /*$pid->product_id*/
$q = explode(',',$q_total); /*in the form of 2,3,4.....*/ /*$q->quantity*/
/*checking start*/
$errors = array();
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
if($quants > $quantity_rem){
$array = array();
$array['errquant'] = 'wrong_quant';
$array['error_pr'] = $ps;
$errors[] = $array;
}
}
echo json_encode($errors);
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
$array = array();
if($quants > $quantity_rem){
$array[$ps]['errquant'] = 'wrong_quant';
// note little change - you will get array with product ids as key
//and qty error assigned to them
}
echo json_encode($array);
exit; /*stop the rest of the code from executing*/
i am adding products to session as array but before adding that product to session how to check that product is present in session array or not.
If the product is present i want to increase the count of that product, if not add that product to session array. My php code is given below.
session_start();
if(empty( $_SESSION['fields1'] )) {
$_SESSION['fields1'] = array();
}
$qty = 1;
$id = $_POST['id'];
$name = $_POST['name'];
$description = $_POST['description'];
$cnt = 0;
print_r($_SESSION['fields1']);
if (! empty($_SESSION['fields1'])){
foreach ($_SESSION['fields1'] as $key=>$val){
if ($id == $val['id']){
$qty = $val['qty']++;
//echo "qty ===".$qty;
$_SESSION['fields1'][$cnt]['qty'] = $val['qty']++;
}
else
{
$arrayval = array('id' => $id,'name' => $name,'description' => $description,'qty' => $qty);
array_push($_SESSION['fields1'] ,$arrayval );
}
$cnt++;
}
}else{
$arrayval = array('id' => $id,'name' => $name,'description' => $description,'qty' => $qty);
array_push($_SESSION['fields1'] ,$arrayval );
}
//print_r($_SESSION['fields1']);
echo json_encode($_SESSION['fields1']);
If $id is ID of product and fields is array of products, try something like this:
if(empty($_SESSION['fields'][$id]))
$_SESSION['fields'][$id]['qty'] = 1;
else
$_SESSION['fields'][$id]['qty']++;
Im trying to create a php function that adds an item to a shopping cart. what i want it to do is check the array to see if the item is already in there, if it is increase the quantity, if not create the item in the cart.
What it is doing instead is it adding an item, it'll work the first time (if the items already there it'l just increase the quantity) but if you add another item it keeps on creating new instances of that item in the shopping cart
e.g
item 1 - quantity 4
item 2 - quantity 1
item 2 - quantity 1
item 2 - quantity 1... and so on...
below is the code i have so far?
function add_item ($id, $qty)
{
$count=$this->countItems;
echo "uytfdgghjkl;kj<br>";
$added = false;
if($count>0)
{
$i=0;
while($added == false)
{
echo "fghjkl<br>";
$tid = $this->items[$i]->getId();
echo "new ID: ".$tid."<br>";
echo "old ID: ".$id."<br>";
echo $i;
if($tid == $id)
{
$amount = $this->items[$i]->getQty();
$this->items[$i]->setQty($amount+1);
$added = true;
//$i++;
//break;
}
if($added == true)
{
break;
}
else //if($added == false)
{
$this->items[$this->countItems] = new OrderItem($id, $qty);
//$this->total = $total+ ($qty *$price);
$this->countItems++;
$added = true;
//break;
}
//else break;
$i++;
}
}
else
{
$this->items[$this->countItems] = new OrderItem($id, $qty);
//$this->total = $total+ ($qty *$price);
$this->countItems++;
}
}
The problem is that you aren't searching the whole array first to see if the item is present in it. The code below should work, but I may have made a typo or something else so make sure you double check it.
function add_item ($id, $qty)
{
$count=$this->countItems;
echo "uytfdgghjkl;kj<br>";
$added = false;
if($count>0)
{
for($i=0; $i < $count; $i++)
{
echo "fghjkl<br>";
$tid = $this->items[$i]->getId();
echo "new ID: ".$tid."<br>";
echo "old ID: ".$id."<br>";
echo $i;
if($tid == $id)
{
$amount = $this->items[$i]->getQty();
$this->items[$i]->setQty($amount+1);
$added = true;
break;
}
}
}
if(!$added)
{
$this->items[$this->countItems] = new OrderItem($id, $qty);
//$this->total = $total+ ($qty *$price);
$this->countItems++;
}
}
An even better option would be to use a dictionary
ie.
$arr = array();
$arr['item_id'] = new OrderItem(...);
Then you can check if the item is in the array using:
if(isset($arr[$id])){
...
}
The logic is flawed. The code will increment the item's quantity only if it happens to be the first item in the cart. Otherwise, it will add the item. Evidenced here:
if($added == true) // if this cart item's quantity was incremented
{
break;
}
else // add item
{
$this->items[$this->countItems] = new OrderItem($id, $qty);
// etc...
}
Instead, you should remove the new OrderItem($id, $qty) from the loop and check the value of $added after looping through all the cart items. For this to work, you need to loop via for (instead of a while) using $count.
class Products extends CI_Controller{
function __construct(){
parent::__construct();
// Load cart library
$this->load->library('cart');
// Load product model
$this->load->model('product');
}
function index(){
$data = array();
// Fetch products from the database
$data['products'] = $this->product->getRows();
// Load the product list view
$this->load->view('products/index', $data);
}
function addToCart($proID){
// Fetch specific product by ID
$product = $this->product->getRows($proID);
// Add product to the cart
$data = array(
'id' => $product['id'],
'qty' => 1,
'price' => $product['price'],
'name' => $product['name'],
'image' => $product['image']
);
$this->cart->insert($data);
// Redirect to the cart page
redirect('cart/');
}
}