PHP - Simple add item to cart and display results - php

I want to use sessions to count how many items are added to the cart. Below I have a submit button that pulls product_id from database along with title and description:
$query = 'SELECT * FROM products ORDER BY date_added DESC';
// Run the query:
if($r = mysql_query($query,$dbc)) {
while ($row = mysql_fetch_array($r)) {
// Print out the returned results:
print "<p><h3>{$row['title']}</h3> {$row['description']}<br />
<form action='add_to_cart.php' method='get'>
<input type='hidden' name='add2cart' value='{$row['product_id']}' />
<input type='submit' value='Add to Cart' />
</form>
</p><hr />\n";
}
}
How do I turn the below into a session to handle my form when add to cart button is submitted. This script I created just counts the cookie every time the page is called or refreshed so it is not accurate. I want to send unique product id and add item to cart using sessions so the items in cart only go up when the add to cart button is clicked.
<?php
if(!isset($_COOKIE['countItems'])){
$Items = 0;
setcookie('countItems', $Items);
}
else{
$Items = ++$_COOKIE['countItems'];
setcookie("countItems", $Items);
}
define('TITLE' , 'Items in cart');
include('templates/header.html');
?>
<div id="main">
<?php
require_once('config.php');
$dbc = mysql_connect(DB_HOST , DB_USER , DB_PASSWORD);
mysql_select_db(DB_DATABASE, $dbc);
if(isset($_COOKIE['countItems'])){
print "<p>You have $Items items in your shopping cart </p>";
print "<p><a href='store.php'>Continue Shopping</a></p>";
}
else{
print "You have not added any items into your cart.";
}
?>
I just need it to output what you see, it doesn't need to be a itemized or anything, just needs to count how many items are in cart and what there ids are.

session_start();
if (! isset($_SESSION['countItems']))$_SESSION['countItems'] = 0;
else $_SESSION['countItems']++;
$Items = $_SESSION['countItems'];
then continue with define('TITLE' , 'Items in cart');

Related

Trying to create a simple shopping cart in PHP with sessions

I've got an assignment where we're supposed to create an eCommerce website that pulls products from a database, lists them and allows you to add them to a cart, though only a single quantity of the item is required but it must have other functions as well, which I think I could figure out on my own.
What I'm trying to work on right now is actually adding items to my cart when the user clicks on the "Buy Now" button I've created for each item pulled from the database but I'm so bloody lost. I'm trying to use a session for the cart so everything is erased when the browser is closed.
Here's what I've got for the page that lists the items available:
<?php
$id = $_GET['id'];
$sql = "SELECT * FROM products WHERE id=$id";
$result = mysqli_query($connection, $sql);
echo '<div id="description">';
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
echo '<h2>'.$row['Name'].'</h2>';
echo '<p>'.$row['Description'].'</p>';
echo 'Buy Now - $'.$row['Price'].'.00';
}
}else{
echo "There is something wrong.";
}
echo '</div>';
?>
And here's what I've got for the cart:
<?php
require('connection.php');
session_start();
$cart_content = array();
?>
I haven't gotten past creating the bones for the array that will be the cart items. I don't know if I'm having an off-morning or what, but I can't seem to figure out how to add items with the buttons I have created. When I think about doing it, it seems like it should be easy but I just can't figure it out, no matter the tutorials I look at. For now, this is the only thing I need help with because I'm pretty sure I can figure out the rest on my own.
First as you are using an anchor tag to launch the CART processing you need to add the id to the querystring
<?php
session_start();
// show all products in this script
$sql = "SELECT * FROM products";
$result = mysqli_query($connection, $sql);
echo '<div id="description">';
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
// stop it showing a product if it has already been selected by user
if ( ! in_array($row['id'], $_SESSION['cart'] ) {
echo '<h2>'.$row['Name'].'</h2>';
echo '<p>'.$row['Description'].'</p>';
echo 'Buy Now - $'.$row['Price'].'.00';
}
}
}else{
echo "There is something wrong.";
}
echo '</div>';
?>
Now when you look for $_GET['id'] in the cart processing script it should exist in $_GET['id']. All you need to do is add it to something in the $_SESSION array that you can later view. Its usful to give that array a sensible name in $_SESSION.
<?php
session_start();
require('connection.php');
// add this id to the cart array in the session
$_SESSION['cart'][] = $_GET['id'];
// re-run the first script
header('Location: xxxx.php'); // sorry dont know what the fist script is called
?>

Problems in passing url variables PHP

I have a code for a shopping cart, which uses sessions to store the cart info for visitors/guests.
I dont want visitors to make an account and login just for adding a few items into cart, so that's the reason for the guest cart using sessions.
I used php and the problem is that it is not secure because I am passing product id through the url.
Also when the cart quantity is updated, more values pass through the url.
The links bellow are .text files of the code I am using
https://jameshamilton.eu/sites/default/files/products.txt
https://jameshamilton.eu/sites/default/files/cart.txt
if someone goes to the cart page and looks at the url, (the url looks like this >>>> www.mywebsite.whatever/cart.php?action=remove&id=2
) ,and refreshes the cart page when an item is added to cart, the item will keep increasing in quantity just by refreshing the page.
Is this a real problem? if so how can it be countered?
I was thinking of setting up a session that is auto incremented with random integers (so that it cant be guessed).
The session starts immediately when a user/visitor visits the website and it is inserted into the MySQL database using the auto incremented value from the session.
From then on, anything that the user/visitor adds to cart goes directly into the mysql database table under the session value.
So, the cart items will be displayed by retreating the items added to the database table WHERE the session = session value.
once the user leaves the page the session will be destroyed and the session integer/value added to the database will be deleted also
is this a good approach? are there much simpler and safer ways to implement a guest shopping cart
Product
<?php
//connect to your database here
?>
</head>
<body>
<table border="1">
<?php
$sql = "SELECT id, name, description, price FROM php_shop_products;";
$result = mysql_query($sql);
while(list($id, $name, $description, $price) = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>$name</td>";
echo "<td>$description</td>";
echo "<td>$price</td>";
echo "<td>Add To Cart</td>";
echo "</tr>";
}
?>
</table>
View Cart
</body>
</html>
cart
<?php session_start(); ?>
<?php
//connect to your database here
?>
</head>
<body>
<?php
$product_id = $_GET[id]; //the product id from the URL
$action = $_GET[action]; //the action from the URL
//if there is an product_id and that product_id doesn't exist display an error message
if($product_id && !productExists($product_id)) {
die("Error. Product Doesn't Exist");
}
switch($action) { //decide what to do
case "add":
$_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id
break;
case "remove":
$_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id
if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
?>
<?php
if($_SESSION['cart']) { //if the cart isn't empty
//show the cart
echo "<table border=\"1\" padding=\"3\" width=\"40%\">"; //format the cart using a HTML table
//iterate through the cart, the $product_id is the key and $quantity is the value
foreach($_SESSION['cart'] as $product_id => $quantity) {
//get the name, description and price from the database - this will depend on your database implementation.
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT name, description, price FROM php_shop_products WHERE id = %d;",
$product_id);
$result = mysql_query($sql);
//Only display the row if there is a product (though there should always be as we have already checked)
if(mysql_num_rows($result) > 0) {
list($name, $description, $price) = mysql_fetch_row($result);
$line_cost = $price * $quantity; //work out the line cost
$total = $total + $line_cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\">$name</td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\">$quantity X</td>";
echo "<td align=\"center\">$line_cost</td>";
echo "</tr>";
}
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" align=\"right\">Total</td>";
echo "<td align=\"right\">$total</td>";
echo "</tr>";
//show the empty cart link - which links to this page, but with an action of empty. A simple bit of javascript in the onlick event of the link asks the user for confirmation
echo "<tr>";
echo "<td colspan=\"3\" align=\"right\">Empty Cart</td>";
echo "</tr>";
echo "</table>";
}else{
//otherwise tell the user they have no items in their cart
echo "You have no items in your shopping cart.";
}
//function to check if a product exists
function productExists($product_id) {
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT * FROM php_shop_products WHERE id = %d;",
$product_id);
return mysql_num_rows(mysql_query($sql)) > 0;
}
?>
Continue Shopping
<?php
/*
products table:
CREATE TABLE `products` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`description` TEXT,
`price` DOUBLE DEFAULT '0.00' NOT NULL ,
PRIMARY KEY ( `id` )
);
*/
?>
</body>
</html>

PHP Shopping Cart Add Items

I'm currently working on a shopping cart using PHP, and I'm trying to figure out how to add items to the cart itself using the code I have written. The items from my database are being displayed correctly, but only the last array under $item is being added to the cart. The following displays the items.
$result = mysqli_query($cxn,$sql) or die("<p class='error'>Couldn't connect to server.</p>");
while($row = mysqli_fetch_assoc($result))
{
$product[] = $row;
}
foreach($product as $item)
{
echo "<div class='product'><form method='post'><div class='img_spacer'><div class='image'>";
include "images.inc";
echo "</div></div><div class='name'><h2>".$item['product']."</h2></div>";
echo "<div class='description'><p>".$item['description']."</p></div>";
echo "<div class='price'><p>".$item['price']."</p></div>";
echo "<div class='add_cart'><input type='hidden' name='add' value='yes'>
<input type='submit' name='add_cart' value='Add to Cart'>
</div></form></div>";
}
The following code is for the shopping cart itself. I have it currently set to print_r the sent variables so I can see what information is being posted.
<?php
if(isset($_POST['add']) and $_POST['add'] == 'yes')
{
$selected = "select product_ID, product, price from product where product_ID='".$item['product_ID']."'";
$result2 = mysqli_query($cxn,$selected);
while($row2 = mysqli_fetch_assoc($result2))
{
print_r($row2);
}
}
?>
I also tried adding the $item['product_ID'] variable to make the 'add' input unique, using
<input type='hidden' name='".$item['product_ID']."_add' value='yes'>
but I couldn't figure out how to add another variable to the $_POST array. I should also mention that I'm using sessions for this project, and I'm not quite sure how to add their shopping cart to the $_SESSION variable. How can I fix this?
You'll want to add more hidden fields to your form. At least:
<input type='hidden' name='product_ID' value='".$item['product_ID']."'>
This will add another variable to the $_POST array when the user clicks Add to Cart.
At the start of each page, you should have a call to session_start();. Then, simply assign the values for your cart to session variables like so:
if(isset($_POST['add']) and $_POST['add'] == 'yes') {
if (!isset($_SESSION['cart'])) {
$_SESSION['cart']=array();
}
array_push($_SESSION['cart'], $_POST);
}
Then (when the user places the order) you would scrub the input, to prevent SQL injection, and add a new SQL query, perhaps something like;
//submit selected items
foreach ($_SESSION['cart'] as $cart_item) {
$pid=scrub($cart_item['product_ID']);
$amount=scrub($cart_item['amount']);
$inserted = "INSERT INTO orders (user, product_id, amount, when) VALUES (".$uid.", ".$pid.", ".$amount.", NOW())";
$result3 = mysqli_query($cxn,$inserted);
}
Of course, you'll have to create the function scrub to scrub your input, but that's outside the scope of the question.

Adding 2 or more items to the cart

So here is my problem. I am able to add one item to the cart. But I want to be able to add more items. I am using form and GET method to add the item
require "connect.php";
$query = "SELECT `DVDID`, `NameOfTheDVD`, `Quantity`, `Price` FROM `DVD` ";
$stmt = $dbhandle->prepare($query);
$stmt->execute();
$num = $stmt->rowCount();
if($num>0){
while ($row = $stmt->fetch(PDO::FETCH_OBJ)){
if(!isset($_SESSION['cart'])){
echo "<table border='3' cellpadding='10' position='relative` bottom= '450px' color = 'blue';>";//start table
echo '<div class="DVD ID">';
echo '<tr><td>DVD Id : '.$row->DVDID. '<br></td>' ;
echo '<td>Name Of the DVD : '.$row->NameOfTheDVD.'<br></td>';
echo '<td>Quantity : '.$row->Quantity.'</td>';
echo '<td>Price: '.$row->Price.'</td></tr> ';
$mydvd = $row->DVDID;
$name = $row->NameOfTheDVD;
$Quantity = $row -> Quantity;
$Price = $row -> Price;
First of all I retrieving the products from the database and then adding them tot h cart via Form and GET methods
echo '<input type="hidden" name="id" value="'.$mydvd.'">';
echo '<input type="hidden" name="item" value="'.$name.'">';
echo '<input type="hidden" name="Quantity" value="'.$Quantity.'">';
echo '<input type="hidden" name="Price" value="'.$Price.'">';
echo '<input type="hidden" name="Cart" value="'.$cartItemCount.'">';
//echo '<input type="submit" value="Add To Basket">';
echo ' Add To Basket<br>';
and this is how I am printing the results out
$myid = $_GET['id'];
$DVDname = $_GET['name'];
$Qty = $_GET['Quantity'];
$price = $_GET['Price'];
echo '<div class="DVD ID">';
echo '<h1> Cart </h1>';
echo '<table border="1" cellspacing="1" position="relative" left="250">';
echo "<tr><th> DVD ID<td> " . $myid . "</td></th></tr>";
echo "<tr><th> DVD Name<td> " . $DVDname . "</td></th></tr>";
echo "<tr><th> Quantity<td> " . $Qty . "</td></th></tr>";
echo "<tr><th> Price<td> " . $price . "</td></th></tr>";
echo '</div>';
Thank you for your help
I'm not gonna write the whole codes for you but instead gonna give you some advice, lecture, etc.
First, you need to know what and how to use SESSION in PHP, using session_start(), session_destroy() and $_SESSION variable.
Now, your cart should be stored on a single session variable, and it should be and will be an array of products.
The structure that I would suggest for simplicity sake is:
$_SESSION['cart'] = array(
12 => array('quantity'=>99),
15 => array('quantity'=>10)
);
On the code above, 12 and 15 are product ids serve as keys in the $_SESSION['cart']. That way, it's easier for us to find the product in the array if we need to update some info, like for example, adding or subtracting quantity.
Also, the example above is simple, to make it work, if your going to show the cart, you need to put it on a loop then query the other info from the database as it loops. You will use the ids (keys) for your search query. But, you can also just store other info in the array where the quantity is when you add an item to your cart so you don't need to query each items from the database.
To add an item to a cart, obviously you need to do a $_GET or $_POST. I'm sure you know how to do this already.
Now, if you want multiple-same items, then I suggest each items have their own form with text field for the quantity. I don't know how your website looks like or when and where "customers" can add item to a cart so algorithm, structure, etc might differ.
So if multiple different items, then you'd need the help of javascript to validate the valid values first before posting it on your php script to process. You can make to do that in the php level but I suggest you do it on the javascript level. Here, I'm saying you should have only 1 form for the product list. I recommend not doing this though.
An example for adding or updating a product in the cart. I use GET for this example.
if(isset($_GET['product_id'],$_GET['product_quantity']))
{
$pid = $_GET['product_id'];
$pq = $_GET['product_quantity'];
$_SESSION['cart'][$pid]['qty'] = $pq;
// if you have more, you can just add something like
// $_SESSION['cart'][$pid]['name'] = "Apple";
}
For deleting an item from the cart:
if(isset($_GET['product_id']))
{
$pid = $_GET['product_id'];
unset($_SESSION['cart'][$pid]);
}

for loop repeating same size row in shopping cart page?

i have a shoppingcart page where for loop count session cart but problem is that i'm retrieving sizes values from mySQL database now for loop repeating single row again and again with every products now i want to display different sizes for every products? please help me thanks in advance?
Select Size Query From MySql Table
function get_size($id){
$result=mysql_query("SELECT mywishlist.`sizes`
FROM mywishlist ORDER BY id DESC ")
or die("Id Problem"."<br/><br/>".mysql_error());
while($row=mysql_fetch_assoc($result)){
return $row['sizes'].'<br>';
}
}
Shopping Cart For Loop Condition
<?php
if(is_array($_SESSION['cart'])){
$max=count($_SESSION['cart']);
for($i=0;$i<$max;$i++){
$id=$_SESSION['cart'][$i]['id'];
$q=$_SESSION['cart'][$i]['qty'];
$product=get_product_name($id);
$image=get_product_image($id);
$ids=get_id($id);
$itemcode=get_itemcode($id);
$size=get_size($id);
if($q==0) continue;
?>
<div style="margin-left: -20px;"> <?php echo $sizes; ?> </div>
<input type="hidden" name="size[]" value="<?php echo $sizes; ?>" /></td>
<?php } } ?>
Even I have tried with the help of Session But Still Same Problem
$sizes=$_SESSION['sizes1'];
My MySQL Table Picture I have Two DIfferent Sizes
**SHopping Cart Page **
when you do a return the loop exits
try:
function get_size($id){
$sizes = array();
$result=mysql_query("SELECT mywishlist.`sizes`
FROM mywishlist ORDER BY id DESC ")
or die("Id Problem"."<br/><br/>".mysql_error());
while($row=mysql_fetch_assoc($result)){
$sizes[] = $row['sizes'];
}
return implode('<br>', $sizes);
}
i think i spotted the error still use the code i provided above
and make the following change in your shopping cart for loop condition
$sizes=get_size($id); // instead of $size=get_size($id);

Categories