Problems in passing url variables PHP - 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>

Related

How to increase number in variable each time a button is clicked in php

I am creating a shopping cart which I have created using php. I have two buttons that when clicked allow the user to increase or decrease the quantity of the item.
When the user clicks the plus button the quantity goes up by one, however if they click it again nothing happens. is there a way that I can allow the user to say click the button until the quantity goes up to 20?
Here is my code:
This first part of my code checks to see if the original add to cart button has been clicked on an item. If it is it then gets the ID of the item. Once the item ID has been revived it them checks if a cart session has been created. If no shopping cart session has been found then it will create one. Once the session has been create it will then check for the quantity that has been add to the form. Next it creates an array call item which will hold the ID and quantity for the item.
if(isset($_POST['add_to_cart']) && isset($_GET['id'])) {
$id = $_GET['id'];
// Check if there is a session for the cart set already, if not then set one.
if(!isset($_SESSION['shoppingcart'])) {
$_SESSION['shoppingcart'] = [];
}
$quantity = $_POST["amount"];
$item = [
"id" => $id,
"quantity" => $quantity
];
}
Next on the cart file the code checks if there is a cart session and that there is at least one item. If there is at least one item in the cart then the code will one a for each loop to get each item from the database.
if(isset($_SESSION['shoppingcart']) && count($_SESSION['shoppingcart']) != 0) {
$list = $_SESSION['shoppingcart'];
$total = 0;
foreach($list as $item) {
$id = $item['id'];
$query = "SELECT * FROM item WHERE ItemID = '$id'";
$result = mysqli_query($mysqli, $query);
$row = $query_result->fetch_assoc();
if (mysqli_num_rows($result) == 1){
$row = mysqli_fetch_array($result);
$id = $row['ItemID'];
$name = $row['ItemName'];
$image = $row['ItemImage'];
$price = $row['Price'];
$size = $row['Size'];
$quantity = $item['quantity'];
$subtotal = $price*$quantity;
$total += $subtotal;
?>
HTML:
<form action="#" method="post">
<h4>Quantity: </h4>
<input type="submit" value="+" name="plus" id="plus" />
<input type="text" class="form-control" id="quanitiy" name="quantity" value= <?php echo "$quantity"; ?>>
<button type="submit" name="minus"><i class="bi bi-dash"></i></button>
</form>
PHP:
<?php
if(isset($_POST['plus']) && ($quantity < 20)){
$_SESSION['quantity'] = $quantity++;
} ?>
I know that this code is in victim of sql injections, I will be fixing it once I get this part working.
$quantity doesn't seem to actually be defined anywhere in your code. It's a bit unclear how even the first increment works, based on what you've shown. Perhaps you omitted some detail from the question?
Based on the information available though, this would seem to be more logical:
<?php
session_start();
if(isset($_POST['plus'])) {
$quantity = (isset($_SESSION['quantity']) ? $_SESSION['quantity'] : 0);
if ($quantity < 20) {
$quantity++;
$_SESSION['quantity'] = $quantity;
}
}
This will check for an existing value, and use that as the starting point to increment from. If there's no existing value it will start from 0.

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
?>

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]);
}

PHP - Simple add item to cart and display results

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');

Categories