I am doing a shopping cart and I am not sure where or rather which page do I code my INSERT INTO statement.
viewProducts.php
<?php
if (isset($_SESSION['cartCity'])) {
$sql = "SELECT * FROM productsc WHERE id_product IN (";
foreach ($_SESSION['cartCity'] as $id => $value) {
$sql .= $id . ",";
}
$sql = substr($sql, 0, -1) . ") ORDER BY id_product ASC";
$query = mysql_query($sql);
if (!empty($query)) {
while ($row = mysql_fetch_assoc($query)) {
?>
<p><?php echo $row['name']; ?><?php echo " x " . $_SESSION['cartCity'][$row['id_product']]['quantity']; ?></p>
<?php
}
} else {
echo "<i>You need to add an item to your cart for it to be visible here</i><br />";
}
} else {
echo "<p>Your cart is empty. <br/> Please add some products</p>";
}
echo "<a href='viewProductsCity.php?page=cartCity'>Go to Cart</a>";
echo "<a href='checkout.php'>Checkout</a>";
?>
or should i add in cart or viewAdd(this is where the codes for when the customer clicks on add to cart button runs) page?
I would create a separate page to do that.
Then, I would include it just by redirecting the user there or by calling it with AJAX. When user got the cart with something, then yeah, we would redirect him to the checkout, and ask him if he wants to buy now or keep shopping.
Related
For a school project, I have to make a webshop with PHP and use a database to search for your products, I have the code to display the results, however, I want to make a link, so that when you click on one of the search results, you go to that product's page.
I've tried looking online but I couldn't seem to find it anywhere, that's why I'm posting this question.
$sql = "SELECT ProductID, ProductTags, ProductName FROM producttabel";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
echo '<div class="allepccskop">';
echo "Onze producten: " . "<br>";
echo '</div>';
while($row = $result->fetch_assoc()) {
echo '<div class="allepccs">';
echo $row["ProductName"]. "<br>";
echo '</div>';
}
} else {
echo "0 results";
}
I want to make a link when you click on one of the search results, you go to that product's page.
To make a link to a product page, you need to use html a tag, just wrap it around your product name like this:
echo '' . $row["ProductName"]. "<br>";
The href attribute contains your php file name (e.g. index.php) and a GET parameter id to send the product id to the php page.
Full example:
Assuming you want to extend your code to display a single product when a product id (ProductID) is provided or all products otherwise.
This is a simple example how you could extend your code, look at the comments:
<?php
// take id from the request, otherwise set default to null
$productId = isset($_GET['id']) ? intval($_GET['id']) : null;
// when we have an id in the url, then we display a product page
if (!is_null($productId)) {
$sql = 'SELECT ProductID, ProductTags, ProductName FROM producttabel WHERE ProductID = ' . $productId;
$result = $mysqli->query($sql);
if ($result && $result->num_rows == 1) {
$row = $result->fetch_assoc();
$result->free(); // free result set
// output data of each row
echo '<div class="allepccskop">';
echo "Product page: #" . $productId . "<br>";
echo '</div>';
echo '<div class="allepccs">';
echo $row["ProductName"]. "<br>";
echo '</div>';
} else {
echo "Product not found";
}
// otherwise we show All products page
} else {
// your code
$sql = 'SELECT ProductID, ProductTags, ProductName FROM producttabel';
$result = $mysqli->query($sql);
if ($result && $result->num_rows > 0) {
// output data of each row
echo '<div class="allepccskop">';
echo "Onze producten: " . "<br>";
echo '</div>';
while ($row = $result->fetch_assoc()) {
echo '<div class="allepccs">';
echo '' . $row["ProductName"]. "<br>";
echo '</div>';
}
$result->free(); // free result set
} else {
echo "0 results";
}
}
i have been making a small shopping cart . and i am trying to display the cart
value and there grand total. i have successfully display the cart product but i
couldn't show grand total. it has been showing error 'Resource id #5' . please check my code below .
viewcart.php
<?php
include('config.php');
session_start();
echo $session=$_SESSION['user_email'];
echo $query=mysql_query("SELECT product_price, SUM(product_price) FROM cart where user_email='$session' GROUP BY user_email");
$total = mysql_fetch_array($query);
$query1=mysql_query("select * from cart where user_email='$session'");
$num_rows = mysql_num_rows($query1);
if($num_rows>0){
echo "<center>";
echo "<table style='width:80%' border=5px><tr><th>Product Name</th>
<th>Product Details</th><th>Product Price</th></tr>";
while($query2=mysql_fetch_array($query1))
//if($query2>0){
{
echo "<tr><td>".$query2['product_name']."</td>";
echo "<td>".$query2['product_details']."</td>";
echo "<td>".$query2['product_price']."</td>";
echo "<td><a href='remove.php?id=".$query2['id']."'>Remove Product</a></td>";
echo "</tr>";
}
echo "<tr><td>Total:</td><td>".$total['product_price']."</td></tr>";
?>
</table>
</center><br/><br/><?php } else { echo "<center>No product available for display!!</center>"; }?>
$query = mysql_query("SELECT SUM(product_price) as sum FROM cart where user_email='".mysql_real_escape_string($session)."'");
$total = 0;
if ($result=mysql_fetch_assoc($query)) {
$total = $result['sum'];
}
I was wondering if anyone can help me save the shopping cart to a database? ive looked all online but havent found anything.
im trying to save an ordering form (for a mock restaurant) to the db after the user adds the items to the cart and proceeds to the pay function which already directs them to paypal screen. So basically, im trying to save the dishes the user selects and the price/qty to the database,address along with an order id.
In the database i have a table called dishes (Id,name,Description,Price and Quantity).
Many Thanks
below is the php session code.
<?php
session_start();
$page = 'ordering.php';
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db ('cart') or die (mysql_error());
if (isset($_GET['add'])) {
$quantity = mysql_query('SELECT id, quantity FROM dishes WHERE id='.mysql_real_escape_string((int)$_GET['add']));
while ($quantity_row = mysql_fetch_assoc($quantity)){
if ($quantity_row['quantity']!=$_SESSION['cart_'.(int)$_GET['add']]){
$_SESSION["cart_".(int)$_GET['add']]+='1';
}
}
header('Location: '.$page) ;
}
if (isset($_GET['remove'])) {
$_SESSION['cart_'.(int)$_GET ['remove']]--;
header('Location: '.$page) ;
}
if (isset($_GET['delete'])) {
$_SESSION['cart_'.(int)$_GET ['delete']]='0';
header('Location: '.$page) ;
}
function dishes(){
$get = mysql_query('SELECT id, name, description, price FROM dishes WHERE quantity > 0 ORDER BY id DESC');
if (mysql_num_rows($get)==0) {
echo "There are no dishes to display!";
}
else {
while ($get_row = mysql_fetch_assoc($get)) {
echo '<p>'.$get_row['name'].'<br />'.$get_row['description'].'<br />€'.number_format($get_row['price'], 2).' Add</p>';
}
}
}
function cart() {
$total = 0;
foreach($_SESSION as $name => $value) {
if ($value>0) {
if (substr ($name, 0, 5)=='cart_'){
$id = substr($name, 5, strlen ($name)-5);
$get = mysql_query('SELECT id, name, price FROM dishes WHERE id='.mysql_real_escape_string((int)$id)) ;
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
echo $get_row['name'].' x '.$value.' # €'.number_format($get_row['price'], 2). ' = €'.number_format($sub, 2).' [-] [+] [Delete]<br />';
}
}
$total += $sub;
}
}
if ($total == 0) {
echo "no items.";
}
else {
echo 'Total: €'.number_format($total, 2).'</p>';
?>
<html>
<p>
<form action='viewcart.php' method='POST'>
<input type='submit' name='view' value='Confirm'>
</p>
<?php
}
}
?>
This is the html file to display the dishes and cart.
<div class="callout">
<aside class="sidebar">
<br />
<fieldset>
<?php cart(); ?>
</fieldset>
</div>
<br />
<?php dishes (); ?>
</body>
<?php include 'footer.html'; ?>
</html>
im trying to save it but im getting a id per item and i want a id per order and also i wanted the total price but its coming back empty
here is my code for inserting into database
function orders() {
foreach($_SESSION as $name => $value) {
if ($value !=0) {
if (substr ($name, 0, 5)=='cart_'){
//-5 so it = to the id number
$id = substr($name, 5, strlen ($name)-5);
$get = mysql_query('SELECT id, name, price FROM dishes WHERE id='.mysql_real_escape_string((int)$id));
while ($Get_row = mysql_fetch_assoc($get)) {
echo '<input type="text" name="item_name_'.$num.'" value="'.$Get_row['name'].'">';
echo '<input type="text" name="amount_'.$num.'" value="'.$Get_row['price'].'">';
echo '<input type="text" name="quantity_'.$num.'"value="'.$value.'">';
echo '<input type="text" name="total_'.$num.'"value="'.$total.'">';
if(mysql_query("INSERT INTO orders (name,quantity,price) VALUES ('$name','$value','$price')"))
echo"successfully inserted";
else
echo "failed";
}
}
}
}
}
You need an order table and an order details table, when customers place an order, you
insert an new order with customer information and new orderid ,amount paid,....
Insert every cart item, quantity,price to the details table, with the order id
Clear session content.
I have a myList.php which should list all products added to my favourites and compute the total price of products.
here is the code:
<?php
include 'navigation.php'
?>
<div class='sectionContents'>
<?php
if (isset($_GET['action']) && $_GET['action'] == 'removed') {
echo "<div>" . $_GET['prod_name'] . " was removed from favourites.</div>";
}
if (isset($_SESSION['fav'])) {
$ids = "";
foreach($_SESSION['fav'] as $prod_id) {
$ids = $ids . $prod_id . ",";
}
// remove the last comma
$ids = rtrim($ids, ',');
include "db_connect.php";
$query = mysql_query("SELECT prod_id, prod_name, prod_price FROM tbl_product WHERE prod_id IN ('$ids')") or die(mysql_error());
$num = mysql_num_rows($query);
if ($num > 0) {
echo "<table border='0'>"; //start table
// our table heading
echo "<tr>";
echo "<th class='textAlignLeft'>Product Name</th>";
echo "<th>Price (MUR)</th>";
echo "<th>Action</th>";
echo "</tr>";
//also compute for total price
$totalPrice = 0;
while ($row = mysql_fetch_assoc($query)) {
extract($row);
$totalPrice += $prod_price;
//creating new table row per record
echo "<tr>";
echo "<td>{$prod_name}</td>";
echo "<td class='textAlignRight'>{$prod_price}</td>";
echo "<td class='textAlignCenter'>";
echo "<a href='remove_favourite.php?prod_id= {$prod_id}&prod_name={$prod_name}' class='customButton'>";
echo "<img src='shopping-cart-in-php/images/remove-from- cart.png' title='Remove from favourite' />";
echo "</a>";
echo "</td>";
echo "</tr>";
}
echo "<tr>";
echo "<th class='textAlignCenter'>Total Price</th>";
echo "<th class='textAlignRight'>{$totalPrice}</th>";
echo "<th></th>";
echo "</tr>";
echo "</table>";
echo "<br /><div><a href='#' class='customButton'>Home</a></div>";
} else {
echo "<div>No products found in your favourites. :(</div>";
}
} else {
echo "<div>No products in favourites yet.</div>";
}
?>
I use the add_to_fav.php below to add the products to my favourites:
<?php
session_start();
// get the product id
$prod_id = $_GET['prod_id'];
$prod_name = $_GET['prod_name'];
/*
* check if the 'fav' session array was created
* if it is NOT, create the 'fav' session array
*/
if (!isset($_SESSION['fav'])) {
$_SESSION['fav'] = array();
}
// check if the item is in the array, if it is, do not add
if (in_array($prod_id, $_SESSION['fav'])) {
// redirect to product list and tell the user it was added to favourites
header('Location: prod_list.php?action=exists&prod_id' . $prod_id . '&prod_name=' . $prod_name);
}
// else, add the item to the array
else {
array_push($_SESSION['fav'], $prod_id);
// redirect to product list and tell the user it was added to cart
header('Location: prod_list.php?action=add&prod_id' . $prod_id . '&prod_name=' . $prod_name);
}
?>
I am having "No products found in your favourites. :(" when i try to view the favourites
I have a counter like thing which shows the number of products in my favourites as well and it stays to 0.
Have I erred somewhere? Which mistake should I correct?
There are a few things that could be happening.
1) You are not starting the session before loading the favorites:
<div class='sectionContents'>
<?php
if(isset($_GET['action']) && $_GET['action']=='removed'){
echo "<div>" . $_GET['prod_name'] . " was removed from favourites.</div>";
}
session_start()
if(isset($_SESSION['fav'])){
2) Your SQL query in fact is not finding any product ids. You might want to debug the SQL and run it in phpmyadmin or your mysql interface to see if it in fact does return any results.
include "db_connect.php";
$query = "SELECT prod_id, prod_name, prod_price FROM tbl_product WHERE prod_id IN ('$ids')";
echo $query; // Print query for debugging
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
My guess is that this query is incorrect because of the single quotes around $ids
It should be:
$query = "SELECT prod_id, prod_name, prod_price FROM tbl_product WHERE prod_id IN ($ids)";
Also this can be simplified from:
$ids = "";
foreach($_SESSION['fav'] as $prod_id){
$ids = $ids . $prod_id . ",";
}
// remove the last comma
$ids = rtrim($ids, ',');
To:
$ids = implode(",", $_SESSION['fav']);
I have a following question. I store a shopping cart in an array session like below
session_start();
$id= $_GET['id'];
if(isset($_SESSION['cart']))
{
array_push($_SESSION['cart'], $id);
}
else
$_SESSION['cart']= array($id);
header("location:cart.php");
And when I try to retrieve the cart. I get the same product id as many as I put to the cart.
<?php
if(!isset($_SESSION['cart'])) {
echo "Your cart is empty.<br /><br /><a href='products.php'>Show products</a>";
} else {
echo '<table border="0.2">';
$total_price = 0;
foreach($_SESSION['cart'] as $id) {
$the_query = "select * from products where id='$id' GROUP BY id";
$result = mysql_query($the_query) or die('Query failed: ' . mysql_error());
$the_product = mysql_fetch_array($result, MYSQL_ASSOC);
$total_price = $total_price + $the_product['price'];
$href = "show_products.php?id=".$the_product['id'];
//echo "<tr>";
echo "<tr><td><a href='$href'>";
echo "<img src='".$the_product['image_url_small']."' /></a></td>";
echo "<td><strong>".$the_product['name']."</strong></td><td><em>$".$the_product['price']."</em>";
echo "</td>";
echo "<td> <a href='do_deletecart.php?id=". $the_product['id'] ."'>Delete item </a></td></tr>";
}
echo "<tr><td colspan='2'></td></tr>";
echo "<tr><td style='text-align:center;font-size:40px;'>$</td><td><strong>Total</strong><br /><em>$".$total_price."</em></td></tr>";
echo "</table>";
echo "<br /><a href='empty_cart.php'>Empty Cart</a> <a href='showallproducts.php'>Show phones</a><br /><br />";
}
how can I make it show only one product id or name. Thank in advance
If I understand your question correctly, you are getting many results for the same product id. This is because you are storing same id values many time in the $_SESSION variable.
You could do the following to not repeat the same ids in the $_SESSION variable.
EDIT
For sake of completeness I have updated the code. Hope that helps.
index.php
<?php
session_start();
$id= isset($_GET['id']) ? $_GET['id'] : null;
if(!is_null($id)){
if(isset($_SESSION['cart']) && count($_SESSION['cart']) > 0){
// increment product quantity if already exists
// or create a new one
add_or_increment_product_to_cart($id, $_SESSION['cart']);
} else {
// initialize cart
// add the first product
$_SESSION['cart'] = array();
array_push($_SESSION['cart'], (object) array('id' => $id, 'quantity' => 1));
}
}
function add_or_increment_product_to_cart($id, $cart){
foreach ($cart as $key => $product) {
if($id == $product->id){
$product->quantity++;
return;
}
}
array_push($_SESSION['cart'], (object) array('id' => $id, 'quantity' => 1));
}
header("location:cart.php");
Cart.php
<?php
session_start();
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : null;
if($cart) {
foreach ($cart as $key => $product) {
$the_query = "SELECT * FROM products WHERE id=" . $product->id . " LIMIT 1";
// your code to fetch the products from the database
// what you have done is fine but vulnerable
// PDO recommended
}
} else {
echo "Your cart is empty.<br /><br /><a href='products.php'>Show products</a>";
}
Also please note that mysql_connect is deprecated and PDO class is the recommended and safe way to connect to the database. Your code is vulnerable to SQL Injection like #Touki said in his comment.
I would recommend performing only one query to retrieve all of the products, and then iterate the result of the query to populate the HTML. For example;
$the_query = "select * from products where id in (". implode(',', $_SESSION['cart']) .")";
$result = mysql_query($the_query);
while (($the_product = mysql_fetch_array($result, MYSQL_ASSOC))) {
...
}
This has the added bonus that you only perform one query, and would also only select one row per product.
It's worth noting, however, that the mysql_* methods are deprecated, and it would be advisable to start using another library such as mysqli or PDO.
On a related note, this code currently is very liable to SQL injection, and the input should ideally be sanitised before being put into a query string.