save order cart session to database - php

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.

Related

UPDATE table with checkboxes

I have the facility to update what I call 'documents' (ver similar to creating a post) on my cms which works fine but I have introduced categories where the documents are associated to them. Now I have managed to bind them when creating the doc from new but when trying update them I am getting a bit stuck. I am using checkboxes to show the list of categories and when selected it updates a join table which uses the doc_id and the cat_id.
Here is the script for updating the doc:
<?php
include ('includes/header.php');
require ('../../db_con.php');
echo '<h1>Document Edit</h1>';
// Check for a valid document ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_docs.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
exit();
}
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
// Check for a document name:
if (empty($_POST['doc_name'])) {
$errors[] = 'You forgot to enter your document name.';
} else {
$dn = mysqli_real_escape_string($dbc, trim($_POST['doc_name']));
}
// Check for a document content:
if (empty($_POST['doc_content'])) {
$errors[] = 'You forgot to enter your last name.';
} else {
$dc = mysqli_real_escape_string($dbc, trim($_POST['doc_content']));
}
if (empty($errors)) { // If everything's OK.
// Test for unique doc title:
$q = "SELECT doc_id FROM docs WHERE doc_name='$dn' AND doc_id != $id";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 0) {
// Make the query:
$q = "UPDATE docs SET doc_name='$dn', doc_content='$dc', doc_name='$dn' WHERE doc_id=$id LIMIT 1";
$r = mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
$doc_id = mysqli_insert_id($dbc);
$query = "UPDATE doc_cat_join (cat_id,doc_id) VALUES ";
$cat_ids = $_POST['cat_id'];
$length = count($cat_ids);
for ($i = 0; $i < count($cat_ids); $i++) {
$query.='(' . $cat_ids[$i] . ',' . $doc_id . ')';
if ($i < $length - 1)
$query.=',';
}
// Print a message:
echo '<p>The document has been edited.</p>';
} else { // If it did not run OK.
echo '<p class="error">The document could not be edited due to a system error. We apologize for any inconvenience.</p>'; // Public message.
echo '<p>' . mysqli_error($dbc) . '<br />Query: ' . $q . '</p>'; // Debugging message.
}
} else { // Already used.
echo '<p class="error">The document name has already been used.</p>';
}
} else { // Report the errors.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p>';
} // End of if (empty($errors)) IF.
} // End of submit conditional.
// Always show the form...
// Retrieve the document's information:
$q = "SELECT * FROM docs WHERE doc_id=$id";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // Valid document ID, show the form.
// Get the document's information:
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
// Create the form:
echo '<form action="edit_doc.php" method="post">
<p>Document Name: <input type="text" name="doc_name" size="15" maxlength="15" value="' . $row[1] . '" /></p>
<textarea name="doc_content" id="doc_content" placeholder="Document Content" style="display: none;"></textarea>
<iframe name="editor" id="editor" ></iframe>'
?>
<div class="row">
<div class="col-group-1">
<?php
$q = "SELECT * FROM cats";
$r = mysqli_query ($dbc, $q); // Run the query.
echo '<div class="view_body">';
// FETCH AND PRINT ALL THE RECORDS
while ($row = mysqli_fetch_array($r)) {
echo '<br><label><input type="checkbox" name="cat_id[]" value="' . $row['cat_id'] . '">' . $row["cat_name"] . '</label>';
}
echo '</div>';
?>
</div>
</div>
<br><br>
<input onclick="formsubmit()" type="submit" value="Update Document" name="submit"/>
<?php echo'
<input type="hidden" name="id" value="' . $id . '" />
</form>
<br><br>Back to docs list';
} else { // Not a valid document ID.
echo '<p class="error">This page has been accessed in error.</p>';
}
?>
<?php
mysqli_close($dbc);
?>
So I have three tables:
docs
doc_id
doc_name
doc_content
cats
cat_id
cat_name
doc_cat_join
doc_id
cat_id
the join table related the doc_id and cat_id which then associates them together. I am guessing in my script when I update a doc it will need to delete the rows and then re-insert them? I just need to know a way or the easiest way of updating the join table as I am a tad stuck...
In case of checkbox update you need to delete previous stored checkbox of with appropriate id and insert new one you can't update checkbox as we can't predict how many checkbox will be selected by user....
Case:
It may happen that user remove one checkbox at update time so you will never know which one to be deleted.......
In your code...
docs
doc_id
doc_name
doc_content
cats
cat_id
cat_name
doc_cat_join
id
doc_id
cat_id
here you have to delete old checkbox of updation doc,
DELETE FROM doc_cat_join WHERE cat_id = some_id
next you can insert selected checkbox as you are inserting first time...

The object stored into a PHP session gets the wrong value stored

I have created a shopping cart object that works. But when I try to save the object into the session the wrong content of that object is stored. The value that is being saved is the value after the object is cleared from the shopping cart, the empty one.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Testing the Shopping Cart</title>
</head>
<body>
<?php # cart.php
// This script uses the ShoppingCart and Item classes.
//error_reporting(0);
// Create the cart:
session_start();
try {
require('ShoppingCart.php');
require('userMenu.php');
$cart = new ShoppingCart();
// Create some items:
require('Item.php');
require ('Connect.php');
$conn=Connect::doConnect();
$query = "SELECT product_id, product_name, product_price from product";
$result = mysqli_query($conn, $query);
$i=0;
$w = array();
$new_cart;
if ($result->num_rows > 0) {
// output data of each row
echo '<table border='."1".'><form action="cart.php" method="post"><tr><td>';
echo '<b>'."Id produs".'</td><td><b>'."Denumire".'</td><td><b>'."Pret".'</td><td>'."Numar de bucati solicitate".'</td></tr><tr>';
while($row = $result->fetch_assoc()) {
echo '<td>'.$row["product_id"].'</td><td>'. $row["product_name"].'</td><td>'. $row["product_price"]. '</td><td>
<input type="input" value="0" name="quantity[]"><input type="hidden" value="'.$row["product_id"].'" name="item_adjust[]"></td>';
echo '</tr>';
$i++;
$w[$i]=new Item($row["product_id"], $row["product_name"],$row["product_price"]);
$cart->addItem($w[$i]);
//$cart->deleteItem($w[$i]);
}
echo '</td></tr><tr><td colspan="3"><input type="submit" value="Adauga in cosul de cumparaturi" name="adjQ"></td></tr></table>';
//foreach ()
} else {
echo "0 results";
}
$conn->close();
if($_POST["adjQ"]){
echo "In stoc avem ".$i." tipuri de produse";
// Update some quantities:
$cart_items_new = array_combine($_POST['item_adjust'],$_POST['quantity']);
foreach ($cart_items_new as $product_id=>$quantity){
//$item=new Item($product_id,Item->);
//Item $it;
//->updateItem($item->getId($product_id), $qty);
//$cart->updateItem(getId($product_id), $quantity);
$conn=Connect::doConnect();
$query1 = "SELECT product_id, product_name, product_price from product where
product_id='$product_id'";
$result1 = mysqli_query($conn, $query1);
$row1=mysqli_fetch_array($result1);
if($quantity>0){
$cart->updateItem($w[$product_id], $quantity);
echo $product_id.$quantity."+".$row1["product_name"];
}
else{
$cart->deleteItem($w[$product_id]);
}
}
// Show the cart contents:
echo '<h2>Continutul cosului de cumparaturi (' . count($cart) . ' tipuri de produse)</h2>';
echo "The user is " . $_SESSION["user"] . ".<br>";
echo "User type is " . $_SESSION["user_type"] . ".";
$new_cart = unserialize(serialize($cart));
if (!$cart->isEmpty()) {
foreach ($cart as $arr) {
// Get the item object:
$item = $arr['item'];
// Print the item:
printf('<p><strong>%s</strong>: %d # $%0.2f bucata.<p>', $item->getName(), $arr['qty'], $item->getPrice());
} // End of foreach loop!
} // End of IF.
}
echo '</td></tr><tr><td colspan="2"><input type="submit" value="Salveaza" name="session"></td><td></td></tr></form></table>';
if ($_POST['session'])
{
echo "You entered the number ";
$serialize_cart=serialize($new_cart);
$_SESSION["cart"]=$serialize_cart;
}
}
catch (Exception $e) {
}
?>
</body>
</html>
What I am doing wrong when I push the second submit button.
Hey I've had a go at this
I can't test it as I dont have the additional files and cart object but it should be close to error free
I've got a Session variable 'cart' if present we grab it unserialize and were done then can edit the values and save it back out so on
If not present i.e. first hit or cart was deleted we build a new cart from the database (This isnt ideal just for testing as presently your adding every item from the database to the cart?)
If the post or get value of adjQ is present we modify some of the values of the cart object and save it back out to the session variable
If the post or get value of showCart is present we output the current cart
To make this work you might have to tweak your Shopping_Cart Object to support the variables being called and the getCount function and the getAllRows function
I've removed the additional storage of an array of the items from the cart (w) not sure what thats for since you have the data stored in the object dont need to replicate it
All the request variables should be sanitized to prevent injection attacks n so on
I've added a hidden field to trigger the showCart request
Anyway hope this helps
<?php
session_start();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Testing the Shopping Cart</title>
</head>
<body>
<?php # cart.php
// This script uses the ShoppingCart and Item classes.
//error_reporting(0);
// Create the cart:
require('ShoppingCart.php');
require('userMenu.php');
$rowCount = 0;
if(isset($_SESSION['cart']))
{
echo "We have a stored cart in a Session variable, retrieving data ...";
$cart = unserialize($_SESSION["cart"]);
$rowCount = $cart->getCount();
}
else
{
$cart = new ShoppingCart();
// Create some items:
require('Item.php');
require ('Connect.php');
$conn=Connect::doConnect();
$query = "SELECT product_id, product_name, product_price from product";
$result = mysqli_query($conn, $query);
$rowCount = $result->num_rows;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$cart->addItem(new Item($row["product_id"], $row["product_name"],$row["product_price"]));
}
}
$conn->close();
}
if(isset($_REQUEST['adjQ']))
{
echo "In stoc avem ".$rowCount." tipuri de produse";
// Update some quantities:
$cart_items_new = array_combine($_POST['item_adjust'], $_POST['quantity']);
foreach ($cart_items_new as $product_id=>$quantity) {
if($quantity > 0) {
$cart->updateItem($product_id, $quantity);
$conn=Connect::doConnect();
$query1 = "SELECT product_id, product_name, product_price from product where product_id='$product_id'";
$result1 = mysqli_query($conn, $query1);
$row1 = mysqli_fetch_array($result1);
echo $product_id." ".$quantity." + ".$row1["product_name"];
}
else {
$cart->deleteItem($product_id);
}
}
// Show the cart contents:
echo '<h2>Continutul cosului de cumparaturi (' . $rowCount . ' tipuri de produse)</h2>
The user is ' . $_SESSION["user"] . '.<br>
User type is ' . $_SESSION["user_type"] . '.';
if (!$cart->isEmpty()) {
foreach ($cart as $arr) {
// Get the item object:
$item = $arr['item'];
// Print the item:
printf('<p><strong>%s</strong>: %d # $%0.2f bucata.<p>', $arr['item']->getName(), $arr['item']->getQuantity(), $arr['item']->getPrice());
} // End of foreach loop!
echo "Saving card to Session variable";
//New_cart is only set in adjQ request prehaps this code should be there?
$_SESSION["cart"] = serialize($cart);
} // End of IF.
}
if(isset($_REQUEST['showCart']))
{
if ($cart->getCount() > 0) {
// output data of each row
echo '<table border='."1".'><form action="cart.php" method="post">';
echo '<tr><td><b>'."Id produs".'</td><td><b>'."Denumire".'</td><td><b>'."Pret".'</td><td>'."Numar de bucati solicitate".'</td></tr>';
foreach ($cart->getAllRows() as $row) {
echo '
<tr>
<td>'. $row->getProductId() . '</td>
<td>'. $row->getName() . '</td>
<td>'. $row->getPrice() . '</td>
<td><input type="input" value="0" name="quantity[]"><input type="hidden" value="' . $row->getProductId() . '" name="item_adjust[]"/><input type="hidden" value="showCart" name="showCart"/></td>
</tr>';
}
echo '<tr><td colspan="3"><input type="submit" value="Adauga in cosul de cumparaturi" name="adjQ"></td></tr></table>';
} else {
echo "Cart is empty";
}
}
?>
</body>
</html>

php shopping cart display error

First of all, i am sorry if this question has been asked before.I am working on a shopping cart. My current code will only show 1 item in the cart. It means that when i click add to cart on #product1 it will show me #product1 detail in the cart. However when i click add to cart for #product2, it will override the information of #product1.
Here is my code for product:
<div >
<image src="ip5s.jpg">
<p><font color="blue">&nbsp&nbspIphone 5S</font></p>
<p><font color="red">&nbsp&nbspRM1999</font></p>
<p><form name="addcart" method="post" action="processcart.php">
<input type="submit" name="addtocart" value="Add to cart">
<input type="hidden" name="product_id" value="1234" />
<input type="hidden" name="quantity" value="1" />
</form>
</p>
</div>
Here is the code for process.php:
<?php
session_start();
include_once("config.php");
$pid=$_POST['product_id'];
$_SESSION['product'] = array($pid);
sleep(2);
echo "Add to cart successful";
header("refresh:1;url=cart.php");
exit();
?>
Here is the code for cart.php:
<?php
if(!isset($_SESSION['cart']))
echo "<p>Your shopping cart is empty!</p>";
else{
$tblname="products";
require_once("dbcon.php");
$proids = array();
foreach($_SESSION['product'] as $id)
{
$proids[] = $id;
}
$proids = implode(',', $proids);
$query = "SELECT * from $tblname where product_id in ('$proids') ";
$result = mysql_query($query) or die(mysql_error());
echo "<table>";
while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
echo "<tr><td>" . $row[$i]['product_name'] . "</td><td>" . $row[$i]['product_price'] . "</td></tr>" ;
}
echo "</table>";
mysql_free_result($result);
mysql_close();
}
Add session_start() to the beginning of cart.php to resume the session.
Also, in order to add multiple product IDs to the $_SESSION['product'] variable, which is probably what you'll be doing, you'll have to change
$_SESSION['product'] = array($pid);
to
$_SESSION['product'][] = $pid;
Which inserts $pid to the end of $_SESSION['product'] array.
USE array_push() .make an array with card Ids and display them using forloop
<?php
session_start();
include_once("config.php");
$pid = $_POST['product_id'];
$_SESSION['product'] = array();
$_SESSION['product'] = array_push($_SESSION['product'], $pid);
sleep(2);
echo "Add to cart successful";
header("refresh:1;url=cart.php");
exit();
?>
Try
<?php
session_start();
if(isset($_SESSION['quantity']))
$_SESSION['quantity']=$_SESSION['quantity']+1;
else
$_SESSION['quantity']=1;
echo "Cart=". $_SESSION['quantity'];
?>
As you seem to be really stuck on this:
process_cart.php
<?php
session_start();
include_once("config.php");
// test & generate cart if needed
if(! isset($_SESSION['cart']))
{
$_SESSION['cart'] = array("products"=>array());
}
// add current product
// ! note: you need to add data validation to this to avoid SQL injects
$_SESSION['products'][$_POST['product_id']] = $_POST['quantity'];
// Show you have done something
sleep(2);
echo "Add to cart successful";
header("refresh:1;url=cart.php");
exit();
?>
databaseConnection.php
<?php
define("DB_HOST", "localhost");
define("DB_NAME", "onlinestore");
define("DB_USER", "root");
define("DB_PASSWORD", "");
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_NAME);
?>
cart.php:
<?php
session_start();
if (!isset($_SESSION['cart']))
{
// No items yet added to the cart
echo "<p>Your shopping cart is empty!</p>";
}
else
{
// set table
$tblname = "products";
// get connection
require_once('DatabaseConnection.php');
// create a list with product ID's
$prodids = array();
// For each product in the cart
foreach($_SESSION['cart']['products'] as $id => $qntity)
{
// add id to the array
$prodids[] = $id;
}
// combine into a string
$prodids = implode(',', $prodids);
$query = "SELECT * from $tblname where product_id in ($prodids) ";
// (The query should really be mysqli)
$result = mysql_query($query) or die(mysql_error());
echo "<table>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "<tr><td>" . $row['product_name'] . "</td><td>" . $row['product_price'] . "</td></tr>". $_SESSION['cart']['products'][$row['product_id']];
}
echo "</table>";
mysql_free_result($result);
mysql_close();
?>

insert data into database for shopping cart

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.

Filter results by Product Type and Sort List by Price (PHP/SQL)

I'm in the process of learning how to create an e-commerce site. I'm trying to figure out how to order product results by price. Code below is a menu list to either filter a specific product category or the option to view all products--the code for that works.
I'm not sure how to add code to "sort by price" (low to high, high to low).
I've tried creating a function called priceList and calling inside the function categoryList (which queries the database for which product type or to view all products), but does not work.
function priceList() {
$con = getConnection();
if($pUserCat == "lowToHigh") {
$sqlQuery = "SELECT Price from Products
ORDER BY Price ASC";
} elseif($pUserCat == "highToLow") {
$sqlQuery = "SELECT Price from Products
ORDER BY Price DESC";
// Execute Query -----------------------------
$result = mysqli_query($con, $sqlQuery);
if(!$result) {
echo "Cannot do query" . "<br/>";
exit;
}
$row = mysqli_fetch_row($result);
$count = $row[0];
if ($count > 0) {
echo "Query works" . "<br/>";
} else {
echo "Query doesn't work" ."<br/>";
}
// Display Results -----------------------------
$num_results = mysqli_num_rows($result);
for ($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc ($result);
// print_r($row);
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['Image']).'" />';
echo "Price: " . stripslashes($row['Price']);
}
// Close connection
closeConnection($con);
}
Form
<!--category and price form ------------------------- -->
<form action="register_script.php" name="frm" method="post">
<select name="category" id="category">
<option value="viewall">View All</option>
<option value="dress">Dress</option>
<option value="athletic">Athletic</option>
<option value="sandals">Sandals</option>
</select>
<input type="submit" value="Go" />
</form>
<form action="register_script.php" name="frm" method="post">
<select name="price" id="price">
<option value="lowToHigh">Low to High</option>
<option value="highToLow">High to Low</option>
</select>
<input type="submit" name="orderPrice" value="orderPrice" />
</form>
</div>
PHP
<?php
function categoryList($pUserCat=false) {
echo "I am in category list" . "<br/>";
$con = getConnection();
$sqlQuery = "SELECT * from Products";
if($pUserCat == "athletic") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='athletic'";
} elseif ($pUserCat == "dress") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='dress'";
} elseif ($pUserCat == "sandals") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='sandals'";
} elseif ($pUserCat == "viewall") {
$sqlQuery = "SELECT * from Products";
}
// Execute Query -----------------------------
$result = mysqli_query($con, $sqlQuery);
if(!$result) {
echo "Cannot do query" . "<br/>";
exit;
}
$row = mysqli_fetch_row($result);
$count = $row[0];
if ($count > 0) {
echo "Query works" . "<br/>";
} else {
echo "Query doesn't work" ."<br/>";
}
// Display Results -----------------------------
$num_results = mysqli_num_rows($result);
for ($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc ($result);
// print_r($row);
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['Image']).'" />';
echo "Price: " . stripslashes($row['Price']);
}
// priceList();
$priceOrder = getPriceBtn(); //$priceOrder holds value of option selected in
//price order menu
priceList($priceOrder);
// Close connection
closeConnection($con);
}
function getPriceBtn() {
//echo "<br/>"."I am calling getPriceBtn function" . "<br/>";
$priceBtn = $_POST["orderPrice"]; // price button
return $price;
//echo $priceBtn;
}
?>
I think you need to pass the $pUserCat to the function priceList($pUserCat);
A tip, you should have a default query like from high to low and if the other option is selected then run that query:
$sqlQuery = "SELECT Price FROM Products ORDER BY Price DESC";
if($pUserCat == "lowToHigh") {
$sqlQuery = "SELECT Price FROM Products ORDER BY Price ASC";
}
Also you could re-write this:
$sqlQuery = "SELECT * from Products"; // is this needed?
if($pUserCat == "athletic") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='athletic'";
} elseif ($pUserCat == "dress") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='dress'";
} elseif ($pUserCat == "sandals") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='sandals'";
} elseif ($pUserCat == "viewall") {
$sqlQuery = "SELECT * from Products";
}
like this categoryList($pUserCat):
if($pUserCat != 'viewall') {
$sqlQuery = "SELECT * FROM Products WHERE ProductType='%s'";
$sqlQuery = sprintf($sqlQuery, $pUserCat);
} else {
$sqlQuery = "SELECT * from Products";
}
Local function variables are not shared. If a function variable is defined within a function, then a function that you call from within that function does not have access to the parent's local variables, which is the very reason they are called "local". You need to pass the variable as a parameter:
When defining:
function priceList( $pUserCat ) {
...
}
When calling:
priceList( $pUserCat );

Categories