I am building an e-commerce application through video tuition.
I have a process_transaction function that parses PayPal tx params from the URL upon a successful purchase and populates an 'orders' table in phpMyAdmin 4.8.0.
Previously, if your refreshed my thank_you.php page the orders continue to populate my 'orders' table (as there was previously no session destroy built into the aforementioned function).
The problem is, the code suggested to prevent such by our tutor for this function does not work. When run, the 'orders' table is no longer populating from the transactions nor is session_destroy operational.
I was wondering what is wrong with the function.
thank_you.php
<?php require_once("../resources/config.php"); ?>
<?php require_once("../resources/cart.php"); ?>
<?php include('../resources/templates/front/header.php') ?>
<?php process_transaction(); ?>
<!-- Page Content -->
<div class="container">
<h1 class="text-center">THANK YOU</h1>
<h3>Nippon will get your products shipped today</h3>
</div>
<!-- /.container -->
<?php include('../resources/templates/front/footer.php') ?>
cart.php (not working properly - does not persist orders in db, or session destroy)
<?php
function process_transaction() {
if(isset($_GET['tx'])) {
$amount = $_GET['amt']; // get amount
$currency = $_GET['cc'];
$transaction = $_GET['tx']; //
$status = $_GET['st']; // get status ie completed
$total = 0;
$item_quantity = 0;
foreach ($_SESSION as $name => $value) {
if($value > 0 ) {
if (substr($name, 0, 8) == "product_") {
$length = strlen($name);
$id = substr($name, 8, $length);
$send_order = query("INSERT INTO orders (order_amount,order_transaction,order_status,order_currency) VALUES('{$amount}','{$transaction}','{$status}','{$currency}')");
$last_id = last_id();
confirm($send_order);
$query = query("SELECT * FROM products WHERE product_id = " . escape_string($id) . " ");
confirm($query);
while($row = fetch_array($query)) {
$product_price = $row['product_price'];
$product_title = $row['product_title'];
$sub = $row['product_price'] * $value;
$item_quantity += $value;
$insert_report = query("INSERT INTO reports (product_id, order_id, product_title, product_price,product_quantity) VALUES ('{$id}','{$last_id}','{$product_title}','{$product_price}','{$value}')");
confirm($insert_report);
}
$total += $sub;
echo $item_quantity;
}
}
}
session_destroy();
} else {
redirect("index.php");
}
}
functions.php
function query($sql) {
global $connection;
return mysqli_query($connection, $sql);
}
function fetch_array($result) {
return mysqli_fetch_array($result);
}
function escape_string($string) {
global $connection;
return mysqli_real_escape_string($connection,$string);
}
Related
I hope you are doing great. I'm having a problem where I cannot insert data into my database. There are multiple reasons to why that happens so don't consider it a duplicate question please. I checked my code. For one table it saves the data but for this table. It displays that the same page was not found and no data is saved on the local database. I hope you can help me guys. Thanks in advance. :)
Here are some useful pieces of code:
<?php
include 'Header.php';
?>
<style>
#first {
//margin-right: 100%;
//clear: both;
}
#first > img {
display: inline-block;
//float: left;
}
#first > p {
//float: left;
display: inline-block;
//margin-left: 60px;
//margin-bottom: 120px;
}
</style>
<!-- Post content here -->
<!-- Then cmments below -->
<h1>Comments</h1>
<!--<?php ?>
if (isset($_GET['id'])) {
$id = $_GET['id'];
} elseif (isset($_POST['id'])) {
$id = $_POST['id'];
} else {
echo '<p class="error"> Error has occured</p>';
include 'footer.html';
exit();
}
$db = new Database();
$dbc = $db->getConnection();
$display = 10; //number of records per page
$pages;
if(isset($_GET['p']) ) //already calculated
{
$pages=$_GET['p'];
}
else
{
//use select count() to find the number of users on the DB
$q = "select count(comment_id) from comments";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$records=$row[0];
if($records > $display ) //calculate the number of pages we will need
$pages=ceil($records/$display);
else
$pages = 1;
}
//now determine where in the database to start
if(isset($_GET['s']) ) //already calculated
$start=$_GET['s'];
else
$start = 0;
//use LIMIT to specify a range of records to select
// for example LIMIT 11,10 will select the 10 records starting from record 11
$q = "select * from users order by $orderby LIMIT $start, $display";
$r = mysqli_query($dbc, $q);
/*if ($r)
{*/
$result = mysql_query("SELECT * FROM comments WHERE video_id= '" + + "'");
//0 should be the current post's id
while($row = mysql_fetch_object($result))
{
?>
<div class="comment">
By: <!--<?php /* echo $row->author; //Or similar in your table ?>
<p>
<?php echo $row->body; ?>
</p>
</div>
<?php
/*} */
?>*/-->
<h1>Leave a comment:</h1>
<form action="Comment.php" method="post">
<!-- Here the shit they must fill out -->
<input type="text" name="comment" value="" />
<input type="hidden" name="submitted" value="TRUE" />
<input type="submit" name="submit" value="Insert"/>
</form>';
<?php
if (isset($_POST['submitted'])) {
$comment = '';
$errors = array();
if (empty($_POST['comment']))
$errors[] = 'You should enter a comment to be saved';
else
$comment = trim($_POST['comment']);
if (empty($errors)) {
include 'Comments_1.php';
$comment_2 = new Comments();
$errors = $comment_2->isValid();
$comment_2->Comment = trim($_POST['comment']);
$comment_2->UserName = hamed871;
$comment_2->Video_Id = 1;
if ($comment_2->save()) {
echo '<div class="div_1"><div id="div_2">' .
'<h1>Thank you</h1><p> your comment has been'
. ' posted successfully</p></div></div>';
}
}
//First check if everything is filled in
/* if(/*some statements *//* )
{
//Do a mysql_real_escape_string() to all fields
//Then insert comment
mysql_query("INSERT INTO comments VALUES ($author,$postid,$body,$etc)");
}
else
{
die("Fill out everything please. Mkay.");
}
?>
id (auto incremented)
name
email
text
datetime
approved--> */
}
?>
<!--echo '--><div id="first">
<img src="http://www.extremetech.com/wp-content/uploads/2013/11/emp-blast.jpg?type=square" height="42" width="42"/>
<p>hamed1</p>
</div><!--';-->
<dl>
<dt>comment1</dt>
<dd>reply1</dd>
<dd>reply2</dd>
</dl>
<!--//}
/*else
{
}*/
?>-->
<?php
include 'Footer.php';
?>
My Comment class:
<?php
include_once "DBConn.php";
class Comments extends DBConn {
private $tableName = 'Comments';
//attributes to represent table columns
public $comment_Id = 0;
public $Comment;
public $UserName;
public $Video_Id;
public $Date_Time;
public function save() {
if ($this->getDBConnection()) {
//escape any special characters
$this->Comment = mysqli_real_escape_string($this->dbc, $this->Comment);
$this->UserName = mysqli_real_escape_string($this->dbc, $this->UserName);
$this->Video_Id = mysqli_real_escape_string($this->dbc, $this->Video_Id);
if ($this->comment_Id == null) {
$q = 'INSERT INTO comments(Comment, User_Id, Video_Id, Date_Time) values' .
"('" . $this->Comment . "','" . $this->User_Id . "','" . $this->Video_Id . "',NOW()')";
} else {
$q = "update Comments set Comment='" . $this->Comment . "', Date_Time='" . NOW() ."'";
}
// $q = "call SaveUser2($this->userId,'$this->firstName','$this->lastName','$this->email','$this->password')";
$r = mysqli_query($this->dbc, $q);
if (!$r) {
$this->displayError($q);
return false;
}
return true;
} else {
echo '<p class="error">Could not connect to database</p>';
return false;
}
return true;
}
//end of function
public function get($video_id) {
if ($this->getDBConnection()) {
$q = "SELECT Comment, Date_Time, UserName FROM Comments WHERE Video='" . $userName."' order by time_stamp";
$r = mysqli_query($this->dbc, $q);
if ($r) {
$row = mysqli_fetch_array($r);
$this->Comment = mysqli_real_escape_string($this->dbc, $this->Comment);
return true;
}
else
$this->displayError($q);
}
else
echo '<p class="error">Could not connect to database</p>';
return false;
}
public function isValid() {
//declare array to hold any errors messages
$errors = array();
if (empty($this->Comment))
$errors[] = 'You should enter a comment to be saved';
return $errors;
}
}
?>
Output show when I click insert button:
Not Found
The requested URL /IndividualProject/Comment.php was not found on this server.
Apache/2.4.17 (Win64) PHP/5.6.16 Server at localhost Port 80
I encountered this kind of issue when working on a staging site because webhosting may have different kinds of restrictions and strict. Now what I did is changing the filename for example:
Class name should match the filename coz it's case sensitive.
Comment.php
class Comment extends DBConn {
function __construct () {
parent::__construct ();
}
//code here..
}
I am a rookie in PHP and I'm trying to make a shopping website for a college module.
Here is my products page that lists all of the products:
//Get the category from the URL
$category = $_GET['category'];
echo("<h1>Products: $category</h1>");
echo("<FORM METHOD='LINK' ACTION='products.php'>");
echo("<INPUT TYPE='submit' VALUE='Back'>");
echo("</FORM>");
echo("<hr>");
//Include database file with settings im
require "db.inc";
//Store the connection in a variable for later use
$connection = mysql_connect($hostname, $username, $password);
//Check for connection
if(! $connection )
{
die('Could not connect: ' . mysql_error());
}
//If the category is all then
if($category == "All")
{
$query = "SELECT * FROM products";//Select everything
}
//If it's not then..
else
{
$query = "SELECT * FROM products WHERE category = '$category'";
}
//Open the Database
mysql_select_db($dbname);
//Start the query
$result = mysql_query($query, $connection);
if(!$result )
{
die('Could not retrieve data: ' . mysql_error());
}
//Loop through the rows and display each object
while($row = mysql_fetch_array($result))
{
//Define all variables we will use
$productid = $row['id'];
$productname = $row['name'];
$productdescription = $row['description'];
$productimage = $row['image'];
$productprice = $row['price'];
$productstock = $row['stock'];
//Display each product and it's info
echo("<h3>$productname</h3>");
echo("<a href=$productimage><img border='0' alt=$productname src=$productimage width='100' height='100'></a><br>");
echo("$productdescription<br>");
echo("<b>Price:</b> £$productprice (ex VAT)<br>");
echo("<b>Stock:</b> $productstock<br>");
//Create a link for each product, that goes to the add to cart script with the product id in the URL
//Only if youre logged in can you see this button
if( isset($_SESSION['login']))
{
echo("<FORM METHOD='POST' ACTION='process_addtocart.php?id=$productid&quantity=1'>");
echo("<INPUT TYPE='submit' VALUE='Add to Cart'>");
echo("</FORM>");
}
echo("<hr>");
}
As you can see it gets all the products from the db and adds a button that links to the addcart php file with the id and quantity to add.
Here is my add to cart function:
<?php
//Make sure user is logged in first
if( isset($_SESSION['login']))
{
//Setup our shopping cart if it isnt already setup into an array table to hold item info
if( empty($_SESSION['shoppingcart']))
{
$_SESSION['shoppingcart'] = array();
}
$id = $_GET['id'];
$quantitytoadd = $_GET['quantity'];
if( isset( $_SESSION['shoppingcart'][$id]))
{
//CODE TO ADD TO QUANTITY????
}
array_push($_SESSION['shoppingcart'], $id);
echo("Item has been added to your cart!");
}
else
{
echo("<p>Please login to add items to your shopping cart!</P>");
}
?>
How would I make it increment a quantity value for THAT specific ID in the array table each time?
Would it be something like:
array_push($_SESSION['shoppingcart'], $id, $quantitytoadd++);
Or you could just increment the product by one with what you have already and make the product ids the key. Keep your inputs clean also.
<?php
//Make sure user is logged in first
if( isset($_SESSION['login']))
{
//Setup our shopping cart if it isnt already setup into an array table to hold item info
if( empty($_SESSION['shoppingcart']))
{
$_SESSION['shoppingcart'] = array();
}
$id = $_GET['id'];
$quantitytoadd = $_GET['quantity'];
if( isset( $_SESSION['shoppingcart'][$id]))
{
//CODE TO ADD TO QUANTITY????
$_SESSION['shoppingcart'][$id]++;
}
else
{
$_SESSION['shoppingcart'][$id] = 1;
}
echo("Item has been added to your cart!");
}
else
{
echo("<p>Please login to add items to your shopping cart!</P>");
}
?>
I want the table tag to come before the display of records in cart() function but it is being displayed after it rather?
How to correct that and in cart() function in the display of records when I am trying <tr> and <td> tags to display its not working
<?php
session_start();
$page = 'index.php';
$connection = mysqli_connect("localhost","root","","cart");
if(isset($_GET['add']))
{
if(array_key_exists('cart_'.$_GET['add'], $_SESSION))
$_SESSION['cart_'.$_GET['add']]+= 1;
else
$_SESSION['cart_'.$_GET['add']] = 0;
header("Location: cartindex.php");
}
if(isset($_GET['remove']))
{
$_SESSION['cart_'.$_GET['remove']]--;
header("Location: cartindex.php");
}
if(isset($_GET['delete']))
{
$_SESSION['cart_'.$_GET['delete']]=0;;
header("Location: cartindex.php");
}
function cart()
{
global $connection;
$total = 0;
?>
<table class="table table-striped"><tr><th>ID</th><th>Name </th><th>Price Per Item</th><th>Cost</th><th>Add</th><th>Substract</th><th>Delete</th></tr>
<?php foreach ($_SESSION as $key => $value) {
if($value > 0)
{
$id = substr($key,5,strlen($key)-1);
$result = mysqli_query($connection ,'select id,name,price from products where id ='.$id);
while($row = mysqli_fetch_assoc($result))
{
$cost = $row['price'] * $value;
echo $row['id'].' '.$row['name'].'#'.$row['price'].'*'.$value.'='.$cost.'[+]'.'[-]'.'[delete]'.'<br>';
$total = $total + $cost;
}
}
}
?></table><?php
if($total==0)
{
///
}
else
{
$dis="'payment made'";
echo 'Total cost is '.$total.'<br>';
echo '<br><button type="button" class="btn btn-success" onclick="alert(\'Payment accepted\');">Success</button>';
}
}
function product()
{
$connection = mysqli_connect("localhost","root","","cart");
if(mysqli_connect_errno())
{
die("not connected to db ".mysqli_connect_error());
}
$get = mysqli_query($connection , "select id,name,description,price from products where quantity > 0 order by id DESC");
while($row = mysqli_fetch_assoc($get))
{
echo '<div class="boxed">'.$row['name'].'<br>'.$row['price'].'<br>'.$row['description'].'<br>ADD'.'<br>'.'</div>';
}
}
?>
Try replace "echo" with "return" inside functions.
I have the following variable $user_id being set by
//Check if user is logged in
session_start();
if (!isset ($_SESSION['user_id']))
{
header("location:login.php");
}
elseif(isset ($_SESSION['user_id']))
{
$user_id = $_SESSION['user_id'];
}
and then within the same function file I have the following:
function course_menu()
{
$sqlSubscription = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'";
$subscriptionResult = mysql_query($sqlSubscription);
while ($rows = mysql_fetch_assoc($subscriptionResult))
{
$user_id = $rows['user_id'];
$course_id = $rows['course_id'];
$course_title = $rows['course_title'];
if ($data_id == $rows['course_id'])
{
echo
'<li>
',$course_title,'
</li>';
}
else
{
echo
'<li>',$course_title,' </li>';
}
}
}
The problem is I keep getting undefined variable user_id every time I try to run the function. I can echo $user_id on another page lets say index.php by using require_once function.php and then echo $user_id, but for some reason the function itself can't access it?
I think it might be because it's outside its scope - but if so I'm not entirely sure what to do about it.
My question is, how can I get the function to be able to use the variable $user_id?
EDIT
So I've started doing
$user_id = $_SESSION['user_id'];
global $conn;
$sqlSubscription = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'";
$subscriptionResult = $conn->query($sqlSubscription);
while ($rows = mysqli_fetch_assoc($subscriptionResult))
{
$user_id = $rows['user_id'];
$course_id = $rows['course_id'];
$course_title = $rows['course_title'];
if ($data_id == $rows['course_id'])
{
echo
'<li>
',$course_title,'
</li>';
}
else
{
echo
'<li>',$course_title,' </li>';
}
}
which seems to work fine, but it's a bit tedious to add a new connection each time with a function or set the $user_id manually. Is there any way around this as I have several functions that require a connection to the db to pull data. Is there a better way to structure this type of stuff? I'm not very familiar with OOP but I can try it out if I can get some direction, here's another function that I use (and there are at least another 5-6 that require db connections)
function render_dashboard()
{
$user_id = $_SESSION['user_id'];
global $conn;
//Following brings up the number of subscription days left on the user dashboard
$sqlDate = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'" ;
$date = $conn->query($sqlDate);
while ($daterows = mysqli_fetch_assoc($date))
{
$course_registered = $daterows['course_title'];
$date_time = $daterows['end_date'];
$calculate_remaining = ((strtotime("$date_time")) - time())/86400;
$round_remaining = round("$calculate_remaining", 0, PHP_ROUND_HALF_UP);
// Here we assign the right term to the amount of time remaining I.E DAY/DAYS/EXPIRED
if($round_remaining > 1)
{
$remaining = $course_registered." ".$round_remaining." "."Days Remaining";
$subscriptionStatus = 2;
echo '<p>',$remaining,'</p>';
}
elseif ($round_remaining == 1)
{
$remaining = $course_registered." ".$round_remaining." "."Day Remaining";
$subscriptionStatus = 1;
echo '<p>',$remaining,'</p>';
}
elseif ($round_remaining <= 0)
{
$remaining = $course_registered." "."Expired"." ".$date_time;
$subscriptionStatus = 0;
echo '<p>',$remaining,'</p>';
}
}
//Check for most recent viewed video
$sqlVideo = "SELECT `last_video` FROM users WHERE `user_id` = '".$user_id."'" ;
$videoResult = $conn->query($sqlVideo);
if ($videoRows = mysqli_fetch_assoc($videoResult))
{
$last_video = $videoRows['last_video'];
$videoLink = "SELECT `chapter_id` FROM chapters WHERE `chapter_title` = '".$last_video."'";
if ($chapteridResult = mysql_fetch_assoc(mysql_query($videoLink)));
{
$chapter_id = $chapteridResult['chapter_id'];
}
$videoLink = "SELECT `course_id` FROM chapters WHERE `chapter_title` = '".$last_video."'";
if ($courseResult = mysql_fetch_assoc(mysql_query($videoLink)));
{
$course_id = $courseResult['course_id'];
}
}
}
The function course_menu() will not recognize your $user_id, Since it is outside its scope.
Make use of global keyword to solve this issue.
function course_menu()
{
global $user_id;
// your remaining code .........
The solution to getting around it without using global is to either DEFINE and pass it through ie - define ('var', '$var') then function x($var) or dependency injection as stated here How can I use "Dependency Injection" in simple php functions, and should I bother?
Im currently working on a small university project. To develop a basic e-commerce php site. We have been given code or provided code within seminars which we are then to customise/develop further to our needs.
I am trying to adapt the following code to add an additional piece of information. The cart.php code builds a shopping cart functionality, which displays the product name, quantity and then allows the user to increase/decrease the quantity.
I am attempting to add the users (selected) product size to the shopping cart. Which they can select on product.php. I have already created the database support for this within product.php I just need the users selected option to then appear over in the cart.php.
Im not entirely sure how to do this correctly. My first problem is how do I record the users selection within product.php into a variable which can be transferred over to cart.php.
The second problem is then how to modify the cart.php to do this also, you shall see in cart.php I have attempted to add the product size to the table.
I really would appreciate some guidance with this.
Product.php
<div align="center"><?php
session_start();
//Connect to Session
include "conn.php";
//Retrieve Header
include "header.php";
//Query
//Get Product ID
if (isset($_GET['id'])){
$product_id = $_GET['id'];
//Select Product Attributes Query where Product ID is the selected product ID
$q="SELECT ProductName,img,ProductID,Description,p_spec1,p_spec2,p_spec3,p_spec4,p_spec5,Price,size_1,size_2,size_3,size_4,size_5 FROM Products
WHERE ProductID=$product_id";
//Retrieve and excute query from database and save results into a variable
$result = mysqli_query($_SESSION['conn'],$q);
//Display Product
if ($row = mysqli_fetch_array($result)){ //Create Product Attribute Array
echo "<div>
<p><b>Name:</b>" .$row[0]."</p>
<p><img src=".$row[1]."></p>
<p><b>Product Code:</b>" .$row[2]."</p>
<p><b><u>Product Description:</b></u></p>
<p>".$row[3]."</p>
<p><b><u>Product Spec:</b></u>";
//Count total product specifications and adjust bullet points
for($i=4;$i<9;$i++) {
if($row[$i]!='')
echo "<li>".$row[$i]."</li>";
}
echo"
<p><b>Price: </b>£".$row[9]."</p>
<p><b>Size:</b><select>";
//Count total product sizes available and adjust drop-down menu
for($i=10;$i<15;$i++) {
if($row[$i]!='')
echo "<option>".$row[$i]."</option>";
}
echo"</select>
</p>
</p>
</div>";
}
//Add Item to basket
echo "<div><input type='submit' value='Add to Basket'</div>";
}
//Retrieve Footer
include "footer.php";
?>
</div>
I have assumed in product.php that a variable $product_size will need to be actioned over to cart.php, however how do I collect the users selection into a variable?
Cart.php
<?php
//Start Session
session_start();
include "conn.php"; //Connect to database
include "header.php"; //Retrieve Header
//View the current shopping cart session
function viewcart(){
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
$cart = $_SESSION['cart']; //store the cart array into a variable then display the content
echo "<table border=\"1\"> <tr> <th>Product</th> <th>Size</th> <th>Quantity</th> <th>Action</th></tr>";
foreach ($cart as $product=>$quantity){
$q = "SELECT ProductID FROM Products WHERE ProductName = '$product' LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_id = $row['ProductID'];
echo "<tr><td>$product</td>
<td>$product_size</td>
<td>$quantity</td><td>
-
+ </td> </tr>";
mysqli_free_result($result);
}
echo "</table>";
subtotal($cart); //display the subtotal
} else { //if shopping cart is empty
echo "<p>Your Basket is empty.</p>";
}
}
function subtotal($cart){
$total = 0; //initialise total
if (!empty($cart)){
foreach ($cart as $product => $quantity){
$q = "SELECT Price FROM Products WHERE ProductName ='$product' LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$price = $row['Price'];
$total += $price * $quantity;
}
echo "<p>Total: £$total |
Empty cart</p>";
} else {
unset($_SESSION['cart']); //destroy empty cart
echo "<p>Your Basket is empty.</p>";
}
}
function addproduct($product_id, $product_qty){
$q = "SELECT ProductName FROM Products WHERE ProductID = $product_id LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_name = $row['ProductName']; //get the product name from product id because it is better to display name than id in the cart
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
$cart = $_SESSION['cart'];
if (array_key_exists($product_name, $cart)){ //if the product exists, update quantity
$cart[$product_name] += $product_qty;
}
else { //otherwise, add new product-quantity pair to the array
$cart[$product_name]=$product_qty;
}
$_SESSION['cart'] = $cart; //write the updated array back to session variable
}
else { //if shopping cart is empty
$cart = array($product_name=>$product_qty); //add product and quantity to the shopping cart
$_SESSION['cart'] = $cart; //write the updated array back
}
mysqli_free_result($result);
}
function deleteproduct($product_id, $product_qty){
$q = "SELECT ProductName FROM Products WHERE ProductID = $product_id LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_name = $row['ProductName'];
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
$cart = $_SESSION['cart'];
if (array_key_exists($product_name, $cart)){ //if product exists, update quantity
$cart[$product_name] -= $product_qty;
if ($cart[$product_name] == 0){ //if the qty 0, delete key
unset($cart[$product_name]);
}
}
else { //exception
echo "<p>Error!</p>";
}
$_SESSION['cart'] = $cart; //write array back to session variable
} else {
echo "<p>Error!</p>";
}
mysqli_free_result($result);
}
function emptycart(){
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
unset($_SESSION['cart']);
}
else {
echo "<p>Error!</p>";
}
}
if (isset($_GET['action'])){
if ($_GET['action']=='view'){
viewcart();
} elseif ($_GET['action']=='add'){
if (isset($_GET['product'])){
$product_id = $_GET['product'];
$product_qty = 1; //default product value
addproduct($product_id, $product_qty);
viewcart();
} else {
echo "<p>There is an error?</p>";
}
}
elseif ($_GET['action'] == 'delete'){
if (isset($_GET['product'])){
$product_id = $_GET['product'];
$product_qty = 1; //default product value
deleteproduct($product_id, $product_qty);
viewcart();
}
else {
echo "<p>There is an error!</p>";
}
} elseif ($_GET['action']=='empty') {
emptycart();
viewcart();
}
else {
echo "<p>There is an error! </p>";
}
}
else { echo "<p>There is an error!</p>"; }
include "footer.php"; //template design part
?>
P.S I am aware of SQL injection issues.
Thank You!
I built something similar to this some time ago and faced the same (rather common) problem.
The solution requires you to create a session variable to store the selected product id's. I think I stored one or more arrays into the session and used the information to populate the checkout page.
I also stored the session data in a table so the user could access it between sessions,
but that was a more advanced feature.
Take Away: use a session variable to store an array of product id's
There are some fundamental flaws here.
To start, create valid HTML. Make sure the form is wrapped in <form></form> tags. That form should have an action: <form action="cart.php" method="POST">
Your select for "size" needs to have a name: <select name="productSize">.