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;
Related
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
I apologize in advanced because I believe that my question may be kind of confusing.
I have three different PHP files. The first one asks you how many different products you want (1-20) in which the variable is called $quantity. Once a number is selected from a drop down box, you are taken to the next PHP page that automatically generates a table with $quantity number of rows and in each row there is a dropdown box that is being populated from a database. There is also another column with empty textboxes for the quantity.
Here is the code for that:
<?php
$quantity = "";
$i = 1;
if (isset($_POST['quantity'])) {
$quantity= $_POST['quantity'];
$var = "";
while($row = mysqli_fetch_array($result1)){
$var = $var . "<option>" . $row['product_name'] . "</option>";
}
echo "<left><table border='1' width='1%'><tr><td><center>Product</td><td>Quantity</center></td></tr>";
while ($i <= $quantity){
echo "<tr><td><select name='product[]' size='1'>";
echo $var;
echo "</select></td><td><input name='quant[]' size='5' /></td></tr>";
$i++;
}
echo "</table></left>";
}
?>
Once each product and its desired quantity is entered, the user clicks submit and they are taken to the final PHP page. This PHP page is supposed to be a confirmation page with all of the customer information and their selected products and quantities. HOWEVER, my code is only printing out the LAST product and quantity in the table from the second PHP page. For example if the table is:
Product Quantity
Bed 1
Chair 2
Couch 3
My confirmation page prints out a one row table with ONLY the information for Couch instead of multiple rows with ALL three of those products. Here is my code for the last PHP page:
<body>
<?php
$curTime= "";
$customerbox= "";
$region= "";
$products = $_POST['product']; //I changed this (edit 2)
$quants = $_POST['quant']; //I changed this (edit 2)
if (isset($_POST['curTime'])) $curTime= $_POST['curTime'];
if (isset($_POST['customerbox']))$customerbox= $_POST['customerbox'];
if (isset($_POST['region']))$region= $_POST['region'];
if (isset($_POST['product']))$product= $_POST['product'];
if (isset($_POST['quant']))$quant= $_POST['quant'];
$error= false;
$done=false;
if ((isset($curTime) && empty($curTime))) {
print "Please enter the date.<br/>";
$error = true;
}
if (!isset($_POST['customerbox'])) {
print "Please select your customer.<br/>";
$error = true;
}
if (!isset($_POST['region'])){
print "Please select your region.<br/>";
$error = true;
}
if (!isset($_POST['product'])){
print "Please select your product.<br/>";
$error = true;
}
if ((isset($quant) && empty($quant))){
print "Please enter the quantity.<br/>";
$error = true;
}
else{
$error = true;
$done = true;
}
for ($i =0; $i < count($products); $i++){
echo $products[$i]; //I changed this
echo $quants[$i]; //I changed this
}
?>
<br>
<table style= border-collapse:collapse width="1%"border="2" align="center" <?php if (!$done){ echo "hidden";}?>
<tr>
<th>Date</th>
<th>Customer</th>
<th>Region</th>
<th>Product</th>
<th>Quantity</th>
</tr>
<tr>
<td><center><?php print $curTime?></td></center>
<td><center><?php print $customerbox?></td></center>
<td><center><?php print $region?></td></center>
<td><center><?php print $product?></td></center>
<td><center><?php print $quant?></td><center>
</tr>
</table>
</body>
I believe this problem is occurring because when I am creating the table with $quantity rows, it's continuously naming each dropdown box $product so it's taking the very last value as $product and printing that.
Is there anyway to print out all of the products with their respective quantities?
Thank you in advance!
For your product and quant dropdown boxes you should use name="product[]" and name="quant[]".
This will send an array instead of one value as $_POST variable, and you can then loop over this array by using
$products = $_POST[product];
$quants = $_POST[quant];
for ($i =0; $i < count($products); $i++){
echo $products[$i]; //echo one product
echo $quants[$i]; //echo one quantity
//etc..
}
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>
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.
I've just build shopping cart here
The add to cart button work perfectly adding the product to the cart without refreshing the entire page.
My question is, how to make the basket update the content after hit the add to cart link without refresh the pages
I have code to handle adding a product to the cart and to show the cart content.
<?php
if($what=="addtocart")
{
if ($cart)
{
$cart .= ','.$_GET['product_id'];
}
else
{
$cart = $_GET['product_id'];
}
$_SESSION['cart'] = $cart;
}
echo writeShoppingCart();
?>
and here are the writeShoppingCart() function
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
echo "<table class=table cellpadding=5 cellspacing=0 width=87% border=0>";
echo "<tr class=bold>";
echo "<td width=65>ID Product</td>";
echo "<td>Pattern</td>";
echo "<td>Inst Type</td>";
echo "</tr>";
include "config.php";
global $dbhost,$dbusername,$dbpassword;
$id_mysql = mysql_pconnect($dbhost,$dbusername,$dbpassword);
mysql_select_db($dbname, $id_mysql);
$cart = $_SESSION['cart'];
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
foreach ($contents as $id=>$qty) {
$view2 = "SELECT * FROM $table_product WHERE id='$id'";
$result2 = mysql_query($view2);
while
($baris=mysql_fetch_row($result2))
{
echo "<tr>";
echo "<td>$baris[1]</td>";
echo "<td>$baris[2]</td>";
echo "<td>$baris[3]</td>";
echo "</tr>";
}
}
echo "</table>";
echo "<span class=\"go_cart\">» View Complete Basket</span>";
}
}
is there any clue to make the echo writeShoppingCart(); reload after adding a product to the cart?
you forgot to add session_start() after opening your <?php tag
so I think you're referencing an empty variable when you do this: $_SESSION['cart'] = $cart;
$_SESSION['cart'] stays empty
to use the session variable you ALWAYS have to put session_start right at the top of the page;
<?php session_start();
//your stuff here
?>
I just checked your page out now and I noticed you're working within wordpress, wordpress doesn't support using session variables, so you'll have to look for the page in your theme that receives first control, it's usually the header.php inside your theme directory: /yourroot/wp-content/themes/yourthemename/header.php, you'll have to add the code above right at the top of that page.
also: I alerted the resp returned from the "add-link" and it returns an entire webpage, the php script you call should be outside of wordpress, prefereably in a file you access directly, so that when the result is returned you have only the output of the function you're echo-ing
Please comment if you're still having errors
//code to dynamically change item table;
$(document).ready(function(){
$('a#add-link').bind("click", function(event) {
event.preventDefault();
var url = $(this).attr("href");
$.get(url, function (resp) {
jAlert('Product Has Been Added to Shopping Cart');
//to do the following you have to put your shoppingcart table in a div with the id="shoppingcart"
$("#shoppingcart").html(resp)
});
});
});
PS: because I think you'll forget about this since I'm doing all your code for you.
right now your post page: "http://ksul.kittenpile.com/product.php" is return an entire webpage, which you will notice if you add the line alert(resp); above your jAlert() function.
It shouldn't return an entire webpage, so it shouldn't be printed to the browser the same way your other pages are printed! only the result of writeShoppingCart() should be echoed and NOTHING ELSE!