Am trying to create a checkout table with the following cart objects. If the cart page is loaded, I want all the cart objects inserted into the checkout table and if any of the products is already in the checkout table (probaly someone toggle between the cart page and shopping page) I want to update checkout page as show below.
I will be glad if I can be put through on this. Thanks
<?php
foreach ($gs->getLists('cart') as $ps):
$cart = $gs->getGoods($ps['p_id']);
array_map(function($ps) {
$pid = $ps['p_id'];
$pu = $ps['pu'];
$pn = $ps['pn'];
$pp = $ps['pp'];
$pk = $ps['pk'];
$tp = $pp * $pk;
if (!isset($_id)) {
"INSERT INTO checkout (p_id, pu, pn, pp, pk, tp)
VALUES ('$pid','$pu','$pn','$pp','$pk','$tp')";
}else{
"UPDATE checkout SET pk=:pk, tp=:tp WHERE p_id = 'p_id'";
}
}
?>
....some html
<?php
}, $cart);
endforeach;
?>
The database connection as below
public $kuo = null;
public function __construct()
{
$this->kuo = mysqli_connect($this->host, $this->user, $this->password, $this->database);
if($this->kuo->connect_error){
echo "Fail" . $this->kuo->connect_error;
}
}
Related
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);
}
I am working on a site that uses a MySQL database and coding is made with PHP. I have an upload page with input fields. On this page there is a drop down input field list I put the options with a mysqli_query selection. I have another form on this same page where the user can add a new item to the MySQL database that should be added to the drop down input field as well.
My idea was to put the code that selects the items from MySQL into a function and call it after a new item is added, but I have problems with connection parameters inside the function as they seems to be undefined inside the function. Maybe should I put the connection to another function?
Another thing is that I would like to achieve the above written (to see the new option in the drop-down list) without refreshing the page. Do I need AJAX for achieving that? Now the page is automatically refreshing when pushing the submit button for adding a new item to the list.
Any help is appreciated. Thank you!
Corresponding parts of my code on the page are:
(this is the current working version without the needed solution)
//making the list for the drop down input field
include "./shortscript/connect_to_mysqli.php";
$sql = mysqli_query($dblink, "SELECT DISTINCT * FROM items") or die(mysql_error());
$count = mysqli_num_rows($sql);
$item_list = '<option value=""></option>';
if($count > 0) {
while ($row = mysqli_fetch_array($sql)){
$item_list .= '<option value="'.$row['item_id'].'">'.$row['brand']
.' '.$row['model'].' '.$row['category'].'</option>';
}
}
mysqli_close($dblink);
//test input function
function test_input($link, $data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = mysqli_real_escape_string($link, $data);
return $data;
}
//adding new item on the other form
if(isset($_POST['submit_new item'])) {
include "./shortscript/connect_to_mysqli.php";
$brand = test_input($dblink, $_POST['brand']);
$model = test_input($dblink, $_POST['model']);
$category = test_input($dblink, $_POST['category']);
if($sqlAddCamera =
mysqli_query($dblink, "INSERT INTO items (brand, model, "
. "category) VALUES"
. "('$brand', '$model', '$category')")
or die(mysql_error()));
}
And the connect_to_mysqli.php file looks like:
<?php
//msqli connection
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'xy';
$dblink = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname)
or die(mysql_error());
mysqli_set_charset($dblink, 'utf8');
?>
You can redirect page to itself by calling func. header() like this :
if(isset($_POST['submit_new item'])) {
include "./shortscript/connect_to_mysqli.php";
$brand = test_input($dblink, $_POST['brand']);
$model = test_input($dblink, $_POST['model']);
$category = test_input($dblink, $_POST['category']);
if($sqlAddCamera =
mysqli_query($dblink, "INSERT INTO items (brand, model, "
. "category) VALUES"
. "('$brand', '$model', '$category')")
or die(mysql_error()));
header("location:./filename.php");
}
If you don't want to use AJAX.
I would split the code into an AJAX function, so every time you click to open the dropdown or trigger an action (add an item, delete an item..), it calls to the ajax function corresponding to the action (load,add,delete..)
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>");
}
?>
function cart(){
if (isset($_GET['add_cart'])) {
global $config;
$ip=getIp();
$pro_id=$_GET['add_cart'];
// checking if user already insert that product to cart
$sql="SELECT * FROM cart WHERE ip_add='$ip' AND p_id='$pro_id' " ;
$run_check=mysqli_query($config,$sql);
if(mysqli_num_rows($run_check)>0) {
echo "";
}
else{
$insert="INSERT into cart (p_id,ip_add) VALUES('$pro_id,$ip')";
$run=mysqli_query($config,$insert);
echo "<script>window.open('index.php','_blank')</script>";
}
}
}
i am getting error on mysqli_num_rows it says mysqli_num_row expects two parameter something like that
You need to add single quote for each value. Reference
$insert="INSERT into cart (p_id,ip_add) VALUES('$pro_id','$ip')";
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">.