How to display information in another PHP Page - php

I am having trouble with a mini shopping cart. I have created the mini shopping cart and when a product is added it goes into the Basket page. However, i want to create a checkout page. How do i grab the products in the basket and put it in a checkout page.
So For example, the check out page will look like this
ITEM NAME, ITEM MODEL, ITEM PRICE
TOTAL OF ITEMS
CHECKOUT BUTTON (links to a payment system)
This is my Basket.php code:
<?php
$bikecode = $_GET['id']; //the product id from the URL
$action = $_GET['action']; //the action from the URL
if($bikecode && !productExists($bikecode)) {
die("Product Doesn't Exist");
}
switch($action) { //decide what to do
case "add":
$_SESSION['cart'][$bikecode]++; //add one to the quantity of the product with id $bikecode
break;
case "remove":
$_SESSION['cart'][$bikecode]--; //remove one from the quantity of the product with id $bikecode
if($_SESSION['cart'][$bikecode] == 0) unset($_SESSION['cart'][$bikecode]); //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;
}
if($_SESSION['cart']){
echo "<table width=\"100%\">";
foreach($_SESSION['cart'] as $bikecode => $quantity) {
$sql = sprintf("SELECT BikeCode, Model, Price FROM Bike WHERE BikeCode = '%s';", $bikecode);
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0) {
list($bikecode, $model, $price) = mysqli_fetch_row($result);
$cost = $quantity * $price;
$total = $total + $cost;
echo "<tr><th>BikeCode:</th><th>Model:</th><th>Quantity:</th><th>Price:</th></tr>";
echo "<tr>";
echo "<td align=\"center\">$bikecode</td>";
echo "<td align=\"center\">$model</td>";
echo "<td align=\"center\">$quantity X</td>";
echo "<td align=\"center\">£$cost</td>";
echo "</tr>";
}
}
echo "<tr>";
echo "<td colspan=\"3\" align=\"right\">Total</td>";
echo "<td align=\"right\">£$total</td>";
echo "</tr>";
echo "<tr>";
echo "<td colspan=\"4\" align=\"right\">Empty Cart</td>";
echo "</tr>";
echo "</table>";
}else{
echo "You have no items in your shopping cart.";
}
function productExists($bikecode) {
$sql = sprintf("SELECT * FROM Bike WHERE BikeCode = '%s';", $bikecode);
return mysqli_num_rows(mysqli_query($con, $sql)) > 0;
}
?>

As long as you have a session_start(); on top of every page you should be able to use the exact same foreach loop as you do in this piece of coding. The session with the information would just be carried over to the next page.

Assume you have a page called test.php with the following code:
<?php
session_start();
$_SESSION['test'] = 1;
echo $_SESSION['test'];
?>
Then to access the test variable in othertest.php page,simply do the following:
<?php
session_start();
echo $_SESSION['test']; ?>

You forgot to add session_start() to the top of your php file. I recommend adding session_start() to a separate file and then including that file in each of the php pages that uses session variables.

Related

How do I use $_SESSION to store items in an array and trigger a button swap?

so I'm trying to store shopping cart items by there ID. Once this happens a button needs to appear "Remove from Cart", if I click this button a new button will appear "Add to Cart" but I'm a little bit lost on it from this point. Im new on here so please excuse my mistakes. My code is below:
session_start();
$items[] = $_POST['add'];
if (isset($_POST['add'])) {
$_SESSION['cart'][]=$_POST['add'];
} else if (isset($_POST['remove'])) {
unset ($_SESSION['cart'][$_POST['remove']]);
}
foreach($vend as $vendID=> $items) {
echo "<form action='vend.php' method='post'>";
echo "<article id ='vend-$vendID'>";
echo "<h1 class = 'item-h1' id = 'h1'>{$items['title']}</h1>";
echo "<div class ='item-no'>";
echo "<p class = 'pro-id'><b>Product ID: </b>{$vendID}</p></div>";
echo "</div>";
echo "<div class ='img-div'>";
echo "<img src=../images/{$items['img']} alt='' height='196' width='200'></div>";
echo "<div class='item-p'>";
echo "<p>{$items['desc']}</p></div>";
echo "<div class='pricing'>";
echo "<p><b>Price: $</b>{$items['price']}</p></div>";
//echo "<button name='add' type='submit' value='$vendID'>Add to Cart</button>";
if(isset($_POST['add']) && ($_SESSION['cart'] == $vendID)) {
echo "<button name='remove' type='submit' value='$vendID'>Remove from Cart</button>";
}
else {
echo "<button name='add' type='submit' value='$vendID'>Add to Cart</button>";
}
In your case here what should be done:
session_start();
/* Check if $_SESSION['cart'] exists */
if (!isset($_SESSION['cart'])) {
/* Init cart as empty array */
$_SESSION['cart'] = [];
}
if (isset($_POST['add']) && 0 < $_POST['add']) {
/* Add product id to session cart */
$_SESSION['cart'][$_POST['add']] = 1;
} else if (isset($_POST['remove']) && 0 < $_POST['remove']) {
/* Remove product id from session cart */
unset($_SESSION['cart'][$_POST['remove']]);
}
// I check with `0 < $id` because ids are always positive
foreach($vend as $vendID=> $items) {
echo "<form action='vend.php' method='post'>";
echo "<article id ='vend-$vendID'>";
echo "<h1 class = 'item-h1' id = 'h1'>{$items['title']}</h1>";
echo "<div class ='item-no'>";
echo "<p class = 'pro-id'><b>Product ID: </b>{$vendID}</p></div>";
echo "</div>";
echo "<div class ='img-div'>";
echo "<img src=../images/{$items['img']} alt='' height='196' width='200'></div>";
echo "<div class='item-p'>";
echo "<p>{$items['desc']}</p></div>";
echo "<div class='pricing'>";
echo "<p><b>Price: $</b>{$items['price']}</p></div>";
if(isset($_SESSION['cart'][$vendID])) {
// you have `$vendID` in session cart - then show Remove button
echo "<button name='remove' type='submit' value='$vendID'>Remove from Cart</button>";
} else {
// you DON'T have `$vendID` in session cart - then show Add button
echo "<button name='add' type='submit' value='$vendID'>Add to Cart</button>";
}
// Also don't forget to close `</form>`
}
To remove an item from your cart you are accessing the item based on your $vendID variable. Which would require your item to be stored in $_SESSION['cart'] as an array:
$_SESSION['cart'][0] = "item 1";
$_SESSION['cart'][1] = "item 2";
...
but later in your code you are accessing $_SESSION['cart'] as if it is just a value not an array
adding an item in your code is done with the following line:
$_SESSION['cart'][]=$_POST['add'];
This results in something like this:
//empty cart
$_SESSION['cart'][0] = $vendid;
Turns out I needed a underscore , i had $POST instead of $_POST and it works now, thanks all :)

PHP Multidimensional Arrays + array_key_exists not working correctly

Before i start to explain in details, let me show the screenshot of what I want the result to be.
What I want to achieve is quite simple, display all the items that are added to cart and calculate the total for each individual product. However, looks like my Multidimensional Arrays and array_key_exists didn't do it correctly and that's why didn't get the result i want.
As you can see from the screenshot, if the same product being added to cart, the quantity didn't plus 1 and it just display below the previous item.
products.php -> nothing special, just to display all the products in database
<?php
require 'config.php';
$q = mysqli_query( $db->conn(), "SELECT * FROM product" );
if( mysqli_num_rows($q) > 0 ) { // Check if there are results
while( $row = mysqli_fetch_assoc($q)){
//echo "id: " . $row["id"]. " <br>- Name: " . $row["product_name"]. " " . $row["product_price"]. "";
echo '<p>ID->'.$row['id'].' | '.$row['product_name'].' | $'.$row['product_price'].'
| Add to Cart</p>';
}
}
?>
cart.php
<?php
session_start();
if(isset($_GET['id'])){
require 'config.php';
$id=$_GET['id'];
$q = mysqli_query( $db->conn(), "SELECT * FROM product where id='$id'" );
$row = mysqli_fetch_assoc($q);
$product_name=$row['product_name'];
$product_price=$row['product_price'];
$quantity=1;
$total=$quantity*$product_price;
if(!isset($_SESSION['cart'])){
$_SESSION['cart'][]=[]; //Create session 1st time
}
if(isset($_SESSION['cart'])){
if(!array_key_exists($id,$_SESSION['cart'])){ // if item not in the cart then Add to cart and Quantity plus 1.
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}else {
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity++,$total];
}
echo '<table border="1" cellpadding="10">';
echo '<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Total</th></tr>';
foreach ($_SESSION['cart'] as $key => $row) { // list out all the items in Multi array
echo "<tr>";
foreach ($row as $key2 => $val) {
echo "<th>";
echo $_SESSION['cart'][$key][$key2]." ";
echo "</th>";
}
echo "</tr>";
}
echo '</table>';
}
}
?>
May i know which part of the coding went wrong?
Revisiting the Code in your cart.php File would be of great Benefit here. Below is what you may want to consider:
<?php
$product_name = $row['product_name'];
$product_price = $row['product_price'];
$quantity = 1;
$total = $quantity*$product_price;
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = [];
}
if(isset($_SESSION['cart'])){
// DOES THE PRODUCT ID EXIST IN THE $_SESSION['cart'] COLLECTION?
// IF IT DOESN'T WE CREATE IT AND LET IT BE...
if(!array_key_exists( $id, $_SESSION['cart'] )){
$_SESSION['cart'][$id] = [$id, $product_name, $product_price, $quantity, $total];
}else {
// IF IT ALREADY EXIST; WE SIMPLY GET THE OLD VALUES & APPEND NEW ONE TO IT...
// HERE YOU ASKED FOR array_key_exits($id, $_SESSION['cart']);
// WHICH MEANS $id MUST BE THE KEY HERE
// HERE IS WHERE THE PROBLEM IS....
$storedPrice = $_SESSION['cart'][$id][2];
$storedQuantity = $_SESSION['cart'][$id][3];
$storedTotal = $_SESSION['cart'][$id][4];
$_SESSION['cart'][$id] = [
$id,
$product_name,
$product_price,
$storedQuantity+1,
round( ($storedQuantity+1)*($product_price), 2),
];
}
echo '<table border="1" cellpadding="10">';
echo '<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Total</th></tr>';
foreach ($_SESSION['cart'] as $key => $row) {
echo "<tr>";
foreach ($row as $key2 => $val) {
echo "<th>";
echo $_SESSION['cart'][$key][$key2]." ";
echo "</th>";
}
echo "</tr>";
}
echo '</table>';
}
You have made the mistake, when add a Cart and Update Cart:
So change the following line:
if(!array_key_exists($id,$_SESSION['cart'])){ // if item not in the cart then Add to cart and Quantity plus 1.
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}else {
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity++,$total];
}
Into
$find = false;
if(!empty($_SESSION['cart'])){
foreach($_SESSION['cart'] as $key=>$cart){
if(isset($cart[0]) && $cart[0] == $id){ //Already exists in Cart
$_SESSION['cart'][$key][3] = $_SESSION['cart'][$key][3] + 1; //$_SESSION['cart'][$key][3] is quantity
$_SESSION['cart'][$key][4] = $_SESSION['cart'][$key][3] * $_SESSION['cart'][$key][2] ; //$_SESSION['cart'][$key][4] update the total
$find = true;
}
}
}
if(!$find){ //Not in the Cart
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}
Note: Before check, clear the cookies

PHP Notice: Undefined offset: 36

I have a simple php checkout but when adding the product to basket i get the following error:
PHP Notice: Undefined offset: 36 in C:\inetpub\wwwroot\shopping\cart.php on line 76
If i then refresh the page or go back to add another product it displays a product fine, it seems to be when adding to first product to the cart we get this error. any help would be much appreciated as all the answers i have tried have not worked.
<?php
// connect to the database
include("databasedrop.php");
?>
<div class="post">
<h2>Shopping Basket<span class="title-bottom"> </span></h2>
</div>
<!-- End Post -->
<?php
if (empty($_GET['id'])) {
$_GET['id'] = "";
}
$ProductID = $_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
switch ($action) { //decide what to do
case "add":
$_SESSION['cart'][$ProductID] ++; //add one to the quantity of the product with id $product_id
break;
case "remove":
$_SESSION['cart'][$ProductID] --; //remove one from the quantity of the product with id $product_id
if ($_SESSION['cart'][$ProductID] == 0)
unset($_SESSION['cart'][$ProductID]); //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 (empty($_SESSION['cart'])) {
$_SESSION['cart'] = "";
}
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 $ProductID => $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
if ($stmt = $conn->prepare("SELECT * FROM products WHERE ProductID=?")) {
$stmt->bind_param("i", $ProductID);
$stmt->execute();
$stmt->bind_result($ProductID, $Title, $Description, $Price, $Stock, $Image, $Category, $Status);
$stmt->fetch();
// show the form
}
$total = "";
$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\">$Title</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.";
}
?>
Shot in the dark, but only solution I can see.
Do you ever create the $_SESSION['cart']-array?
Try this:
switch ($action) {
case "add":
if (!isset($_SESSION['cart'][$ProductID])) {
$_SESSION['cart'][$ProductID] = 1;
}
else {
$_SESSION['cart'][$ProductID]++;
}
break;

PHP regex undifined offset when used in function

I have a string consists of multiple lines. I am getting this string from imap (as an email body). I get this string as follows:
$mail_body = imap_fetchbody($mbox,$msgno,1);
My regex is:
preg_match("/HEX}(.*).php/", $string, $matches);
If I describe this string manually like:
$_string = "It is too long therefore I do not paste it here"
And If I do that:
preg_match("/HEX}(.*).php/",$_string,$matches);
$new_string = $matches[1];
echo $new_string;
It works perfectly.
But when I passed string to a function in same class:
$this->some_funtion($mail_body);
It gives me an error although I am doing the same thing in function:
preg_match("/HEX}(.*).php/",$_string,$matches);
$new_string = $matches[1];
echo $new_string;
Error: Notice: Undefined offset: 1
Why should it happen? I am doing the very same thing!
Thanks for your help!
EDIT
private function get_directory_path($string = '')
{
preg_match("/HEX}(.*).php/", $string, $matches);
$new_string = $matches[1];
echo $new_string;
}
I pass parameter as follows:
$mail_body = imap_fetchbody($mbox,$msgno,1.2);
if(!strlen($mail_body)>0){
$mail_body = imap_fetchbody($mbox,$msgno,1);
}
$this->get_directory_path($mail_body);
There are several things that might make the pattern not match. Newlines, spaces and tabs being the biggest problem because when you echo out to the screen and copy/paste to test they don't copy. Perhaps echo out the $mail_body variable inside of <pre> tags before passing it to the function or echo and view the source.
The easy way to fix it is to add the s modifier so that the dot (.) character matches newlines. So /pat{2}ern/s. But that might not give you the result you want. Without a full output of the string and what you expect from it (or what you are using it for), it wouldn't be possible to tell.
<?php
include('dataconn.php');
$result=mysql_query("select * from product");
while($row=mysql_fetch_assoc($result))
{
echo "<p>$row[Product_Name]</p>";
echo "<p>$row[Product_Quantity]</p>";
echo "<p>Add To Cart</p>";
}
?>
logout
/*--add to cart page--*/
<?php
/* ----------- ADD TO CART PAGE ----------------*/
include("dataconn.php");
$product_id = isset($_GET['pid']) ? $_GET['pid'] : null;
$action = isset($_GET['action']) ? $_GET['action'] : null; //the action
$quantity=isset($_GET['qty']) ? $_GET['qty'] : null;
?>
<html>
<head>
<title>View Cart</title>
</head>
<body>
<?php
$customer_id=$_SESSION['customer_id'];
$result=mysql_query("select * from product");
$row=mysql_fetch_assoc($result);
switch($action)
{
//decide what to do
case "add":
$_SESSION['cart'][$product_id]++;
break;
case "remove":
$_SESSION['cart'][$product_id] = 0;
unset($_SESSION['cart'][$product_id]);
header("Location: payment.php");//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.
header("Location: payment.php");
break;
}
//------- for checkout ---------
if(isset($_SESSION['cart']) && $_SESSION['cart']) {
$total = 0;
echo "<form name='cart' method='POST' action=''>";
echo "<table border=\"1\" padding=\"3\" width=\"100%\" class=\"data-container\">";
echo "<td colspan=\"4\" align=\"right\"><img src=\"image/delete.png\"/></td>";
foreach($_SESSION['cart'] as $product_id => $quantity)
{
$sql = sprintf("SELECT * FROM product WHERE Product_ID = %d;", $product_id);
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
$itemsInfo = mysql_fetch_assoc($result);
$cost = $itemsInfo["Product_Price"] * $quantity;
$total = $total + $cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\">".$itemsInfo["Product_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 </td>";
echo "<td align=\"center\">RM $cost</td>";
echo "<td align=\"center\"><img src=\"image/remove.png\"/></td>";
echo "</tr>";
}
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" ></td>";
echo "<td align=\"center\">Total</td>";
echo "<td colspan=\"2\" align=\"center\">RM $total</td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
?>
<br>
<div>
<span style="margin-left: 88%"><input type="submit" name="shopping_more" class="custom-button" value="Back To Shopping"/></span>
</div>
</html>

PHP SESSION HTML table carrying issue

I am adding items to my cart.php using an add in the URL.
case "add":
if (isset($_SESSION['cart'][$comic_id])) {
$_SESSION['cart'][$comic_id]++;
} else {
$_SESSION['cart'][$comic_id] = 1;}
... My items are presented into an HTML table in the cart.php. I just want to then re-call specific variables from the array in the checkout.php so the customer can confirm the order total along with their personal details.
I can only seem to carry the last added item/row over using SESSION variable when I use the following:
$_SESSION['totalnameqty']=$name . " " . $qty . " " . $cost;
...and then use an echo on the checkout.php page:
$totnamqty=$_SESSION['totnamqty'];
echo $totnamqty;
... I want to carry all items $name, $qty & $cost added to the HTML table in the cart.php to the checkout.php not just 1 item/row. Unsure of how to do this or if it is possible. Can somebody help?
Here is my cart.php:
if (isset($_SESSION['cart'][$comic_id])){
echo "<table border=\"0\" padding=\"10\" width=\"80%\">";
echo "<td colspan=\"1\" align=\"left\">Continue Shopping</div>";
echo "<td colspan=\"6\" align=\"right\">Empty Cart</td>";
echo "<tr height=\"20px\">";
echo "<tr height=\"20px\">";
echo "<td align=center>Image</td><td align=center>Title</td><td align=center>Description</td><td colspan=3 align=center>Copies (+/-)</td><td align=center>Price</td>";
echo "<tr height=\"20px\">";
foreach($_SESSION['cart'] as $comic_id => $qty) {
$sql = sprintf("SELECT title, description, cost, image_thumbnail
FROM comic
WHERE comic_id = %d;",$comic_id);
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
list($name, $description, $price, $image_thumbnail) = mysql_fetch_row($result);
$cost = $price * $qty;
$total = $total + $cost;
$cost = number_format($cost,2);
$total = number_format($total,2);
$description = substr($description, 0, 250);
echo "<br><tr>";
echo "<td width=\"10px\" align=\"center\"><img height=100 align=center src=\"$image_thumbnail\">";
echo "<td align=\"center\">$name</td>";
echo "<td width=\"40%\" align=\"center\">$description...<a href=comic_dyn.php?comic_id=$comic_id>More Info</td>";
echo "<td width=\"30px\" align=\"center\">+<br><td align=\"center\">$qty <td width=\"20px\" align=\"center\">-</td>";
echo "<td align=\"right\">$$cost</td>";
echo "</tr>";
}
}
echo "<br><tr><tr height=100px>";
echo "<td><td><td colspan=\"4\" align=\"right\">Total:</td>";
echo "<td width=\"60px\" align=\"right\">$$total</td>";
echo "<tr><td colspan=\"7\" align=\"right\">Proceed to Checkout";
echo "<tr height=\"50px\">";
echo "</table>";
}else{
echo "Your cart is currently empty.";
echo "<br><br><td colspan=\"1\" align=\"left\">Continue Shopping</div>";
}
//session variables (to be carried to checkout.php
$_SESSION['cost']=$cost;
$_SESSION['name']=$name;
$_SESSION['qty']=$qty;
$_SESSION['totnamqty']=$name . " " . $qty . " " . $cost;
You're setting $name, $qty and $cost values inside a loop, therefore you are accessing the last set values below/outside of the loop. Also, you're using $comic_id at the beginning but below are using that same variable in your foreach statement. I'm guessing you can remove the foreach and instead use: $qty = $_SESSION['cart'][$comic_id]?
Otherwise, assuming the isset() at the top is incorrect, and that you are trying to loop each $comic_id from the cart; then you want to index your 'cost', 'name', 'qty' and 'tonamqty' values per $comic_id. eg. use something like this inside your foreach loop: $_SESSION['comics'][$comic_id]['cost'] = $cost;
However, I think a checkout approach without using session variables is more appropriate. I'd post what the user currently sees to checkout.php, rather than using the session data. Assume the session was accessed from multiple tabs and the user clicks checkout on an outdated tab. If using session variables, the server is only aware that the user requested to checkout the most recent items in the session, not what was actively visible.

Categories