PHP Shopping Cart Add Items - php

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.

Related

Cannot pass value from form to variable to be posted

I want to pass some value from my form to be sent with POST. However, when i use dropdown, it wont detect the value and thus giving me undefined index error for every variable
When i use simple text form to post, it works, but i need to use the dropdown form.
dropdown for shop code
<?php $stmt = $shop->readName();
echo "<select class='form-control name='shop_id'>";
echo "<option>select shop name</option>";
while ($row_shop = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row_shop);
echo "<option value='{$shop_id}'>{$shop_name} </option>";
}
echo "</select>";
?>
and the post code
if ($_POST) {
// Set values
$transaction - > customer_id = $_POST['customer_id'];
$transaction - > shop_id = $_POST['shop_id'];
$transaction - > staff_id = $_POST['staff_id'];
// create transaction
if ($transaction - > add()) {
echo "<div class='alert alert-success'>Transaction was created.</div>";
}
// if unable to create the staff, tell the user
else {
echo "<div class='alert alert-danger'>Failed.</div>";
}
}
EDIT : Now the error is gone, but the form simply wont do anything :(
Here's the screenshot of the form
form
Undefined index errors means that you haven't defined $transaction as an object, thus when you try to update one of the values (for example $transaction->customer_id), PHP will give you an error.
Try defining $transaction like so:
$transaction = new yourObjectNameHere();
Just after the if($_POST).

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>

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

Keep selections in php generated form after submit (POST)

I'm currently using php to populate a form with selections from a database. The user chooses options in a select style form and submits this, which updates a summary of the selections below the form before a second submit button is used to complete the interaction.
My issue is that every time a user uses the first submit, the selections that were there previously do not stick. They have to go through the whole form again.
Is there anyway to keep these selections present without resorting to php if statements? There are a ton of options so it would be a pain to use php for each one. Also, form is being submitted via POST.
Sample from form:
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'COLOR' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
I tried using this js snippet to repopulate the selections, but it does not seem to work properly...
<script type="text/javascript">document.getElementById('color').value = "<?php echo $_GET['proudct_cpu'];?>";</script>
This does not seem to work. Any suggestions other than php if statements?
Thanks!
edit: This is basically the form set up I'm using, though I've shortened it significantly because the actual implementation is quite long.
// Make a MySQL Connection
<?php mysql_connect("localhost", "kp_dbl", "mastermaster") or die(mysql_error());
mysql_select_db("kp_db") or die(mysql_error());
?>
<br />
<form action="build22.php" method="post">
<input type="hidden" name="data" value="1" />
<br />
<br />
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'color' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
<input type="submit" value="Update Configuration">
</form>
The selections from the form above get echoed after submission to provide the user with an update as such:
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>&nbsp&nbsp&nbsp&nbsp";echo $_POST['product_color']; ?>
</div>
I assume you're storing the user's selections in a separate table. If that's the case, you'll need to add some logic to determine if you should display the form values or what's already been stored.
<?php
// form was not submitted and a config id was passed to the page
if (true === empty($_POST) && true === isset($_GET['config_id']))
{
// make sure to properly sanitize the user-input!
$rs = mysql_query("select * from saved_configuration where config_id={$_GET['config_id']}"); // make sure to properly sanitize the user-input!
$_POST = mysql_fetch_array($rs,MYSQL_ASSOC); // assuming a single row for simplicity. Storing in _POST for easy display later
}
?>
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>&nbsp&nbsp&nbsp&nbsp";echo $_POST['product_color']; ?>
</div>
So after storing the user's selections in the database, you can redirect them to the page with the new config_id in the URL to load the saved values. If you're not storing the selected values in a table, you can do something similar with cookies/sessions.
echo the variables into the value tag of the form elements. If you post all your code I'm sure I can help you.
UPDATE
ah, so they are dropdown lists that you need to remember what was selected? Apologies, I read your post in a rush yesterday and thought it was a form with text inputs.
I just did a similar thing myself but without trying your code let me see if I can help.
Basically what you need to do is set one value in the dropdown to selected="selected"
When I had to do this I had my dropdown values in an array like so:
$options = array( "stack", "overflow", "some", "random", "words");
// then you will take your GET variable:
$key = array_search($_GET['variablename'], $options);
// so this is saying find the index in the array of the value I just told you
// then you can set the value of the dropdown to this index of the array:
$selectedoption = $options[$key];
This is where it might be confusing as my code is different so if you want to use it you will probably need to restructure a bit
I have a doSelect function to which I pass the following parameters:
// what we are passing is: name of select, size, the array of values to use and the
// value we want to use as the default selected value
doSelect("select_name", 1, $options, $selectedoption, "");
// these are the two functions I have:
// this one just processes each value in the array as a select option which is either
// the selected value or just a 'normal' select value
FUNCTION doOptions($options, $selected)
{
foreach ($options as $option)
{
if ($option == $selected)
echo ("<option title=\"$title\" id=\"$value\" selected>$option</option>\n");
else
echo ("<option title=\"$title\" id=\"$value\">$option</option>\n");
}
}
// this is the function that controls everything - it takes your parameters and calls
// the above function
FUNCTION doSelect($name, $size, $options, $selected, $extra)
{
echo("<select class=\"\" id=\"$name\" name=\"$name\" size=\"$size\" $extra>\n");
doOptions($options, $selected);
echo("</select>\n");
}
I know that's a lot of new code that's been threw at you but if you can get your select values from the db into the array then everything else should fall nicely into place.
The only thing I would add, is at the start where we call doSelect, I would put that in an if statement because you don't want to set something as selected which hasn't been set:
if (isset($_GET['variable']))
{
$key = array_search($_GET['variablename'], $options);
$selectedoption = $options[$key];
doSelect("select_name", 1, $options, $selectedoption, "");
}
else
{
doSelect("select_name", 1, $options, "", "");
}
I hope that helps!

Categories