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]);
}
Related
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>
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.
How can I update a database with the values from an array? For example, let’s say we got a database with three tables:
Meals:
mealnr(PK), name, sort
Ingredients: ingredientnr(PK), name, stock
Structure: mealnr(FK), ingredientnr(FK), amount
I filled the database with some meals and ingredients. Every meal consists of multiple ingredients. The chef decides you only need 75g of ingredient x instead of 100g for meal y, so it needs to be changed in the database. Of course it can be done with SQL-commands, but I want to do it using a form in PHP.
First I made a page where all the meals are displayed. A meal can be edited using the edit-button next to it and based on the mealnr, you can change the amount of one or multiple ingredients for that particular meal. On the edit-page all the ingredient names and amounts are displayed in a table. The amount fields are textfields, those can be edited.
I made this script, but I don’t know exactly how I can update my database with the values of an array. I tried it with a foreach-loop, but it doesn't work.. yet. Can somebody help me?
<?php
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db("eatit", $conn);
$id = $_REQUEST['mealnr'];
$result = mysql_query("SELECT meals.name AS mealname, structure.amount, ingredients.name AS ingredientname
FROM Meals, Structure, Ingredients
WHERE meals.mealnr = structure.mealnr
AND structure.ingredientnr = ingredients.ingredientnr
AND meals.mealnr = '$id'");
if(isset($_POST['save']))
{
$new_amount = $_POST['amount[]'];
foreach ($new_amount as $value) {
mysql_query("UPDATE structure SET amount ='$value', WHERE mealnr = '$id'")
or die(mysql_error());
}
}
mysql_close($conn);
?>
<p><strong>Ingredients:</strong></p>
<?php
echo "<table>";
echo "<tr>";
echo "<th>Ingredient</th>";
echo "<th>Amount (gr)</th>";
echo "</tr>";
while($ingredient = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>";
echo $ingredient['ingredientname'];
echo "</td>";
echo "<td>";
echo '<input type="text" formmethod="post" name ="amount[]" value="' . $ingredient['amount'] . '" />';
echo "</td>";
echo "</tr>";
}
?>
<input type="submit" name="save" value="save" />
In your HTML markup you have declared the elements holding the name amount as an array by using amount[].
So, in your php code that receives the data it's enough to just refer to the amounts this way:
$new_amount = $_POST['amount'];
instead of:
$new_amount = $_POST['amount[]']; // in fact, this is wrong
Your foreach is fine, you should add some checks so that the $value actually contains a value that you expect, for example an int, float or not less than zero (or whatever checks you find necessary).
foreach($new_amount as $value){
if($value != '' && $value >= 1){
//sql statements goes here.
}
}
Receiving form data this way and then directly injecting the result to your SQL statement is always dangerous:
$id = $_REQUEST['mealnr'];
If you declare that you expect an integer (as the id's should be) before you directly inject the code to your SQL statement you have already written safer code.
$id = (int)$_REQUEST['mealnr'];
Also, just for the record - the mysql_* library is deprecated. As pointed out in the comments, try using PDO or mysqli instead - really!
I try to pass a form which contains other forms (same inside forms, dynamic) , but I have checked that the data which are sent to the 'script handler' (php) are incomplete data. I think somewhere buffer is overwriting or something. Here is the code :
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
if($number== 0)
{
header('Location: /ceid_coffee/user_order_form.php');
}
else
{
$_SESSION['number'] = $number;
echo '<form action="user_order_form.php" method="POST">';
for($i=0;$i<$number;$i++)
{
$item = $_SESSION['item'];
echo $item;
$rec_query = "SELECT * FROM ylika";
$rec_result= mysql_query($rec_query) or die("my eroors");
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<br>';
echo '<input type="checkbox" name="yliko[][$i]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';//<~~~~this line is form's data
}
echo '<br>';
}
echo '<input type="submit" name="submit" value="FINAL_ORDER">';
echo '</form>';
}
}
?>
And this is the handling script:
<?php
if (isset($_POST['submit']))
{
$number= $_SESSION['number'];
$item = $_SESSION['item'];
$max_id = "SELECT MAX(id_order) FROM id_of_orders";
$x=mysql_query($max_id) or die("my eroors");
$id= mysql_fetch_array($x);
$xyz = $id['MAX(id_order)'];
for($i=0;$i<$number;$i++)
{
$temp = $_POST['yliko'][$i]; // <~~~~ this line is the form's data
$temp2 = implode("," , $temp);
$inserts = ("INSERT INTO orders (order_id,product,ulika) VALUES ('$xyz' , '$item','$temp2')");
$inc_prod=("UPDATE proion SET Counter = Counter + 1 WHERE proion.onomasia='$item'");
mysql_query($inserts) or die(mysql_error());
mysql_query($inc_prod) or die(mysql_error());
}
}
?>
This line here contains the data of each form , but i have echo them ($temp2) and i saw that they are incomplete.
$temp = $_POST['yliko'][$i];
If i select more than 1 checkbox for each item ($i) I get only one value from the checkboxes into the sql.
Do you see if I miss something ?
Ok i found the error. I replace this row :
echo '<input type="checkbox" name="yliko[][$i]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';//<~~~~this line is form's data
with this row :
echo '<input type="checkbox" name="yliko['.$i.'][]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
I do not know how (i'm new to php) but it worked.
You will only get one value for each form because you are assigning the value of $i to each one:
echo '<input type="checkbox" name="yliko[][$i]" value='. etc.
is your problem line.
Have a look at the HTML that your code produces (ctrl-u in most browsers) and you will see why you get the wrong answer. All your checkboxes need to have unique names.
I would do it by assigning each checkbox a name that relates to the line in the database from which they are drawn eg:
name="checkbox_"'.$row['ylikaprimarykey']."etc.
This will get you up and running fairly quickly. For what it is worth, the ids of your table keys can give attackers information about your site so it is best practice to obfuscate them in some way. There are a number of excellent classes available free on the net that will do this for you.
If you really need to deal with what would have been in each form as a separate chunk of data, you can easily change the checkbox names vis:
name="checkbox_$formnumber_$obfuscatedkeynumber"
then loop through them with nested loops in your handling page.
I don't know how to set up that the id field to print one by one per row in the script below which works wonders.
$tree = array();
$sql = "select * from products
left join product_varieties on product_varieties.product_id = products.id";
$sth = query($sql);
while($row = fetch($sth)) {
$id = $row['id'];
$tree[$id]['name'] = $row['name'];
if($row['variety'])
$tree[$id]['varieties'][] = $row;
}
foreach($tree as $product)
<div>
echo $product['name']
foreach($product['varieties'] as $variety)
etc etc
</div>
I have been trying to use the id generated in the while loop inside the form action url string inside the foreach parent as you use the name index in the partent foreach. I have tried echoing and printing some how it won't display the id or if I print it, then it will appear three rows of ids per rows like 111333444555, I just want to be able to have the id per row like echo $product['name'] does, each iteration only prints one row of the index [ 'name'].
The form below won't echo anything, and I I change it to print then it will print 111222333444 help..
foreach($tree as $product){
<form action="cart.php?id="'. echo $product['id']. '">
</form>
<div> echo $product['name'] echo $procude['id']
foreach($product['varieties'] as $variety) {
etc etc
</div>
}
}
not sure i understand correctly what you want.. but let me try:
foreach($tree as $id=>$product){
echo "<div>".$id." ".$product['name'];
foreach($product['varieties'] as $variety){
// whatever
}
echo "</div>";
}