Not understanding how to add cart into PHP - 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.

Related

Declare order to show foreach output with PHP

I am currently trying to set up a custom sortable list. Without getting into too much detail as this would become a very large post, I would like to use the PHP foreach function to show the list.
I currently have
$video_id = $row['videos'];
$res = preg_replace("/[^0-9,.]/", "",$video_id);
$exclude = explode(',', $res);
} ?>
....
<ul id="sortable2" class="connectedSortable">
<?php foreach ($video_list as $key => $item): ?>
<?php if(in_array($item['id'], $exclude)){ ?>
<li id="video-<?php echo $item['id'] ?>"><?php echo $item['id'],
$item['title'] ?></li>
<?php } ?>
<?php endforeach; ?>
</ul>
This generates a list of items from the database excluding items with an ID from an array which is also fetched from another table.
In this example, it will only show videos with the id 3,4 and 2. This is all working as expected. My issue is once I have reordered the items and refreshed the page they are loaded in numerical order. I need these to be load in the order specified (3,4 and 2 for this example).
Any help would be highly appreciated.
Thanks
I think what you are looking for is ORDER BY FIELD (MySql), this lets you order by a field in a specific way.
I need these to be load in the order specified (3,4 and 2 for this example).
Sounds like a good fit to me!
For example
SELECT * FROM table WHERE id IN(3,4,2) ORDER BY FIELD(id, 3,4,2)
This will select rows from table where the id is in the list and then order the results by id in the order they are place there, 3 then 4 then 2.
excluding items with an ID
This might cause some issue, the Field order by assumes you know at least some of the values in the field. Excluding implies that you know what you don't want but not necessarily what you do want, if that makes sense.
Maybe it's not an issue, I don't have enough information on your particular use case to determine that, so I am just mentioning it as a cautionary thing.
Thanks!

How to delete items in cart with string

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?

mixing two PHP carsto echo a single string value

I need to check if there is a product code in db else assign a product code starting with 101 and add 0001
I am trying like this
$store_code="101";
$product_code=($store_code(0001));
but I get a blank page ...
The result I need is 1010001
any sugestion is welcome
NOTE: the store code comes from MySQL but I show it now like this for an easier understanding
So if I get this correctly, you first check if the product code is in database, and you have no truble doing that.
//lets say $product_code is your code
//if code not in db:
$product_code .= "0001"; //this will add 0001 at the end of the $product_code variable
or
$product_code = $store_code . "0001";

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.

trying to write a proper if statement in php

i am having a hard time wrapping my head around how to do this... i have a select menu i want to display as default and a different one(s) if certain items appear in a shopping cart.
so say i sell dogs and cars. in the cart i have selected one of each. i want one select menu to appear if there are ever any cars in the cart. but if there are ever any dogs in the cart or cats for that matter i want a different select with different options to appear. so car_select would be the default if anything is in the cart...(i sell a lot of stuff) but if a dog appears in the cart then dog_select would replace it.
the way it is written now. the default is the last thing and that is what shows.
(see my comments)
so the code:
<?php
foreach($this->rows as $i => $row){
if (strstr('dogs',$row->dates)) {
$mydates = 'dogs';
} else {$mydates='default';}
//echo $row->dates; this spits out the correct values dogcar
}
//echo $mydates; with a dog and a car in the cart this returns default
//below functions i believe but i think the above is faulty
?>
<?php
if ($mydates =='dogs'){
//do something here;} else {
$type = $this->type;
foreach($this->extraFields[$type] as $fieldName => $oneExtraField) {
if ($fieldName != 'pickupdate-rosh'){; ?>
<tr class="hikashop_checkout_<?php echo $fieldName;?>_line">
<td class="key">
<?php echo $this->fieldsClass->getFieldName($oneExtraField);?>
</td>
<td>
<?php
echo $this->fieldsClass->display($oneExtraField,$this->$type->$fieldName,'data['.$type.']['.$fieldName.']');
?>
</td>
</tr>
<?php } ?>
<?php } ?>
<?php } ?>
i would like to always return car_select unless the presence of dogs or cats etc in the cart.
{edit: i just realized that is not the correct function to use to look for a string.}
It looks like you're setting $mydates, then overriding it (potentially). This is because you're setting one variable to one result for all iterations of your foreach loop, and the last iteration will be what the final variable value will be.
So set $mydates to a default and then change it if the condition is right.
$mydates='default';
foreach($this->rows as $i => $row){
if (strstr('dogs',$row->dates)) {
$mydates = 'dogs';
}
//echo $row->dates; this spits out the correct values dogcar
}

Categories