How to delete items in cart with string - php

I have a shopping cart in my website that has uses a string for the shopping list. Each product has a 3 digit id, so the string looks something like 031181083 with 3 items.
In php,
session_start();
$numbooks = strlen($_SESSION['bookstrings'])/3;
$books = $_SESSION['cart'];
echo "You have " . $numbooks . " books in your Cart.";
echo $_SESSION['bookstrings'];
echo "<br><br>";
include '/redirect.php';
where $_SESSION['cart'] is the string that gets updated when the user adds a product to the cart.
I use a for loop with
${"book$x"} = str_replace("011", "55USD New Traditions and Encounters ", ${"book$x"});
to display the book information instead of the numbers for the user. However, I am having trouble with deleting part of the string when the user cancels the item.
The user presses
echo 'Cancel';
and redirect.php looks like this:
<?php
echo "aaa";
include 'mycart.php';
$x = $_GET['cancel'];
$booksnow = str_replace(${"bookid$x"}, "", $books);
$_SESSION['bookstrings'] = $booksnow;
echo $_SESSION['bookstrings'];
header("Location: mycart.php");
?>
When I go to redirect.php, $_SESSION['bookstrings'] is successfully updated, but when I redirect back to mycart.php, the variable resets.
I don't mind rewriting a lot of stuff, so is there a better way to code the cart? Using a string was the first thing that came to my mind, so built on top of it, but I feel like it's very inefficient, and I would love to use a simpler way with functionality.
PS: when a page opens, the php part does not show up, and when I refresh, it becomes normal. Any ideas?

Related

PHP Sessions Remove Cart Iitems

I have been searching around for help but can't find anything that will fix my problem
I have manipulated a cart code to serve a different a purpose Im bulging a role-play assistance site www.rptoolkit.com/encounter where you add NPC's to the encounter (Cart) and you can then remove them when needed, the site is online if you want to check
the issue is script works perfectly fine in XXMP hosting on my local host but online live, if i add 4 people to the list and try to delete 1 they all clear and the first line gets duplicated (feel free to test)
below is my script code i have used for the delete item button
<h1>Curent Encounter</h1>
<div class="encounter-table">
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["encounter"]))
{
$cart_items = 0;
foreach ($_SESSION["encounter"] as $cart_itm)
{
$id = $cart_itm["code"];
$results = $mysqli->query("SELECT * FROM products WHERE id='$id' LIMIT 1");
$obj = $results->fetch_object();
echo '<td><span>
<a href="include/encounter_remove.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'"><img src="images/icon_delete.gif" alt="Delete"><
/a></span></td>';
and below is the code I have to remove items from the encounter (cart)
<?php
session_start();
include_once("config.php");
//remove item from encounter
if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["encounter"]))
{
$id = $_GET["removep"]; //get the product code to remove
$return_url = base64_decode($_GET["return_url"]); //get return url
foreach ($_SESSION["encounter"] as $cart_itm) //loop through session array var
{
if($cart_itm["code"]!=$id){ //item does,t exist in the list
$product[ ] = array('code'=>$cart_itm["code"]);
}
//create a new product list for cart
$_SESSION["encounter"] = $product;
}
//redirect back to original page
header('Location:'.$return_url);
}
?>
I would love any help or advise i can I've to fix it, I don't know if its coming downy to the different PHP versions from my XXMP to the server possibly?
Thanks again,
Trev
Session variable size can be limited by the browser. Depending on how much data is stored in `$_SESSION['encounter'], you may be reaching the limit. Consider only storing a id numbers or something similar instead of more complex objects and/or arrays.

PHP Variable Spacing Error

I am having an issue with a php variable not including rows that contain spaces. I have it so the user can easily delete something from their list by clicking the x button on the page. The x button contains the link used to delete the item. The issue is the php variable "Item" seems to not fully include items with spaces. If a user click to delete Car Oil then url would become "http://www.example.com/delete.php/?Item=Car". It does not add the space with the rest of the word to allow it to be deleted from the list. Also if I echo the variable $Item it fully has everything so it would it would display Car Oil. Any help would be loved.
$query = mysql_query("select Items, Loc from Members where Username = '$Username' and Session = '$Session'ORDER BY Loc+0 ASC, Items ASC;");
while ($row = mysql_fetch_array($query)) {
$Item = $row['Items'];
echo "<p1>";
echo $row['Items'], ' - Aisle ' .$row['Loc'];
echo "<a href=http://www.example.com/delete.php/?Item=$Item><img src=http://exmample.com/Images/x.png style='margin-bottom:-5px;'></a>";
echo "</p1>";
}
You might need to urlencode the value on your html. For instance
<a href="http://www.example.com/delete.php/?Item=<?php echo urlencode($itemName); ?>">
click here to delete
</a>
Space is not a valid character in a url
Look at urlencode
echo "<img src=http://exmample.com/Images/x.png style='margin-bottom:-5px;'>";

PHP counter file and page forwarding

So i'm writing this code so that you either get forwarded to a certain page if you're the first one to hit the link, or you are sent back to the original page after being displayed a message if you're not what beginner mistake am i making?
<?php
$count = file_get_contents('counter.txt');
$count = trim($count);
if ($count="0")
{
$count = $count + 1;
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
header("Location: newpage.html");
}
else
{
fclose($fl);
echo "Sorry but the item has already been sold out";
header("Location: oldpage.html");
}
?>
As for the delay, you can accomplish it two different ways. The first is to use PHP header (like you are currently doing), but change it to look like this:
<?php
header("refresh:5;url=oldpage.html");
echo "Sorry but the item has already been sold out";
?>
The other way is to echo out a piece of HTML code, the meta-refresh:
<?php
echo '<meta http-equiv="refresh" content="2;url=oldpage.html">';
echo "Sorry but the item has already been sold out";
?>
In both examples, 5 is the amount of seconds until the refresh. Experiment with each one to see if it will fit your needs.
This might be some sort of syntax that I'm not familiar with, but none of my scripts have ever had the
<? code
I simply use
<?
Also since you did not delay our header tag the user will not see the previously echoed statement above it. It will automatically redirect before the page has time to output fully.

Not understanding how to add cart into PHP

I am stuck on this code. I am making a web page and on the side there is a place for a cart. And with the you should be able to click on an item and add it to cart. Well I am having trouble getting it to add it to cart. Can someone help me understand what I should be doing. I have been working on it for a few days and no matter what I am doing nothing is working. If i get the code to show you have 0 in your cart it wont add anything if i try to put it in the cart.
<h1>Cart Contents?</h1>
<div class="p2">
<?php
// Get all the categories and
// link them to category.php.
// Define and execute the query:
$q = 'SELECT category_id, category FROM categories ORDER BY category';
$r = mysqli_query($dbc, $q);
// Fetch the results:
while (list($fcid, $fcat) = mysqli_fetch_array($r, MYSQLI_NUM)) {
// Print as a list item.
echo "<li>$fcat</li>\n";
if($_SERVER['PHP_SELF']!="CART FILE"){
echo "<h1>Cart Contents</h1>";
echo "<div class=\"p2\">";
$itemCount=X;
foreach($_SESSION['cart'] as X=>X){
for($i=0;$i<count(X);$i++){
$itemCount+=X;
}
}
echo "You have ".$itemCount." total items in your cart.";
echo "</div>\n";
} // End of while loop.
?>
<h1>Specials?</h1>
<div class="p2">
<p>Maybe place specials or new items or related items here.</p>
</div>
</div>
<div class="content">
Ok here is a link to what the cart should do if you look over to the side it should do what that one is doing.
http://www.programmerskit.com/advPHP/ch5/
Shouldn't
$itemCount=X;
foreach($_SESSION['cart'] as X=>X){
for($i=0;$i<count(X);$i++){
$itemCount+=X;
}
}
just be:
$itemCount = count($_SESSION['cart']);
I can't otherwise figure out what that code is supposed to be doing.
Also, that code that outputs the cart appears to be in a while loop outputting each item category, so you will be displaying the cart multiple times, which I can only assume is not desired functionality.
Also, another poster made a point about the invalid use of X as a constant, which is also a good point.
You've got a bare X used all over the place. While saying
$somevar = X;
would be legitimate if you'd already done define('X', 'somevalue') previously, this next one
foreach($_SESSION['cart'] as X=>X){
is completely invalid. You cannot assign new values to a defined constant, let alone try to assign TWO different values at the same time
foreach($_SESSION['cart'] as $key => $value)
is how that particular bit of code should be.

Not displaying cookie count correctly

I have one file basket.php that displays the count perfectly, but in the other php file product.php it always displays 0 the codings are below:
basket.php
<?php
//include(dirname(__FILE__)."/../config.php");
if (isset($_COOKIE["products"])) {
//Count of all products in basket
$BasketCount = count($_COOKIE['products']);
//Loop through and get each cookie
foreach ($_COOKIE['products'] as $name) {
$name = htmlspecialchars($name);
echo "$name <a href='remove.php?remove=$name'>Click here to remove from basket</a> <br />\n";
}
echo "Basket Count: $BasketCount";
}else{
echo "Basket is empty";
}
?>
product.php
(just the line that gets the basket count)
$basketcount = count($_COOKIE['products']);
Here is how i set the cookies
addtobasket.php
<?php
include(dirname(__FILE__)."/../config.php");
$product = $_GET['p'];
setcookie("products[$product]", $product);
echo "$product added to basket";
//Show current basket products
?>
May be issue with path - http://www.php.net/manual/en/function.setcookie.php, $path parameter. Or domain.
Not the actual answer, but nevertheless related:
Assuming you're making a commercial website with a basket/shopping cart system, I would advice this:
DO NOT RELY ON COOKIES, never. It's stored on client side and can be modified easily. Moreover some browser simply refuses them, and thus your basket won't work.
Use $_SESSION[] instead, they only store the identifier client side. Safer, both against hacking code flaws and anything.
may be you are running product.php before cookie is set..
other than that code is fine to me.
or you can check cookie is set or not by this code..
if(isset($_COOKIE['products'][$product])){
echo "cookie is set..";
}
so that you will have exact idea..

Categories