I have this code (in Floral.php) that I was given to me as a shopping cart app which works on one (1) web page; I had to dismember it because of the structure of my web pages and now I'm trying to put it back together so it works with multiple web pages (files):
<?php
session_start();
define("PRODUCTCODE", 0);
define("PRODUCTNAME", 1);
define("QUANTITY", 2);
define("PRICE", 3);
var_dump($_POST);
$action = isset($_POST['action']) ? $_POST['action'] : '';
if($action == 'Recalculate') {
RecalculateCart();
}
else if(isset($_POST['Check Out'])) {
header("Location: "."./customer.php");
}
function RecalculateCart() { // something changed, so recalculate everything
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : ''; // get current cart for this session (it's not saved between browser sessions!))
$itemcount = isset($_SESSION['itemcount']) ? $_SESSION['itemcount'] : 0; // get the item count
echo "itemcount from SESSION: " .$itemcount;
for ($i=0; $i < $itemcount; $i++) {
$quantity = $_POST['quantity'.[$i]]; // get quantity of new item
echo "quantity from POST: ".$quantity;
if (empty($quantity)) { // quantity is 'empty' so make it zero (0))
$quantity = 0;
}
else if (($quantity < 0) || (!is_numeric($quantity))) { // validate it
$quantity = 0;
}
$cart[QUANTITY][$i] = intval($quantity); // passed validation, so move it to the cart
}
for ($j=0; $j < $itemcount; $j++) {
$quantity = $cart[QUANTITY] [$j]; // add the quantity of the new item to accumulation
if ($quantity == 0) { // remove item from the cart
$itemcount--;
$curitem = $j;
while(($curitem+1) < count($cart[0])) {
for($k = 0; $k < 4; $k++) {
$cart[$k][$curitem] = $cart[$k][$curitem+1];
$cart[$k] [$curitem+1] = '';
}
$curitem++;
}
}
}
$_SESSION['itemcount'] = $itemcount; // save the item count
$_SESSION['cart'] = $cart; // save cart contents
}
?>
$itemcount is 4, according to the echo, which is correct. $quantity is set in another file and becomes part of $cart (it's from a text field in a form; there is a submit button in that form which does the POST). This is that code (in viewCart.php):
<?php
session_start();
define("PRODUCTCODE", 0);
define("PRODUCTNAME", 1);
define("QUANTITY", 2);
define("PRICE", 3);
$action = isset($_POST['action']) ? $_POST['action'] : '';
if (isset($_POST['productcode'])) {
AddToCart();
}
function AddToCart() {
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : '';
$itemcount = isset($_SESSION['itemcount']) ? $_SESSION['itemcount'] : 0;
$cart[PRODUCTCODE][$itemcount] = $_POST['productcode'];
$cart[PRODUCTNAME][$itemcount] = $_POST['productname'];
$cart[QUANTITY][$itemcount] = intval($_POST['quantity']);
$cart[PRICE][$itemcount] = $_POST['price'];
$itemcount = $itemcount + 1;
$_SESSION['cart'] = $cart;
$_SESSION['itemcount'] = $itemcount;
echo "addToCart-itemcount: ".$itemcount;
}
?>
Being a somewhat of a noob at PHP, I am assuming that the POST in the first code segment is correct, except for the fact it's in another file which makes it NOT global in scope. So does the global keyword apply here? and if so, where do I put it? (in which file and which statement)?
You're using incorrect syntax to access the quantity array item:
$quantity = $_POST['quantity'.[$i]];
The [$i] actually creates a new array containing the item $i (using the array syntax introduced in PHP 5.4), and when you try to use it as a string it gets output as just 'Array'. So it evaluates to $_POST['quantityArray']. If you have notices enabled you should see an "Array to string conversion" notice to help you catch this sort of thing.
So simply change it to:
$quantity = $_POST['quantity'.$i];
Or:
$quantity = $_POST["quantity$i"];
BTW, notices can be quite helpful for detecting bugs, so make sure you have them enabled. Either enable display_errors and error_reporting in php.ini or add this to your code (but make sure you only show errors on your local or development server, since reporting them on a production server can be a security risk):
ini_set('display_errors', 1);
error_reporting(E_ALL);
Related
I have a multidimensional array. The parent array includes items that each item inside is an array with its properties.
insertProduct.php checks everytime I add a new product to the array if the product already exists. If it doesn't it pushes it to the array, if it already exists it finds it and adds +1 to its quantity.
I am trying to create a functionality where pressing a button "Undo" removes the latest addition whether it was a whole product (which means its QTY would be 1 so it removes it altoghether) or if the latest addition was just a QTY increase (from 1 to 2) then remove 1 from the QTY.
However my issue is when I add a product that already exists but is not in the last spot of the array, the QTY does increase as it should be but then the UNDO does not do -1 to this item's QTY.
I don't know if it's alright to post a video but here's the pattern of the problem in a short gif
insertProduct.php
if (isset($_SESSION['myArray'])) {
$inserted_products = $_SESSION['myArray'];
$position = array_search($inserted_product_ean, array_column($inserted_products,0));
//check if new product already exists
if ($position !== false) {
$inserted_products[$position][2] = $inserted_products[$position][2] + 1;
$latest_product = $inserted_products[$position];
$_SESSION['latestProduct'] = $latest_product;
$_SESSION['myArray'] = $inserted_products;
} else {
array_push($inserted_products, $product); //$product is an array of info about the item inserted
$latest_product = $product;
$_SESSION['latestProduct'] = $latest_product;
$_SESSION['myArray'] = $inserted_products;
}
} else {
$latest_product = $product;
$_SESSION['latestProduct'] = $latest_product;
array_push($inserted_products, $product);
$_SESSION['myArray'] = $inserted_products;
}
deleteLastEntry.php
<?php
if (isset($_SESSION['myArray'])) {
$inserted_products = $_SESSION['myArray'];
$inserted_products_length = count($inserted_products);
if ($inserted_products_length > 0){
$latest_product = $_SESSION['latestProduct'];
$qty = $latest_product[2];
if ($qty !== false && $qty > 1) {
$qty = $qty - 1;
$latest_product[2] = $qty;
array_pop($inserted_products);
array_push($inserted_products, $latest_product);
$_SESSION['myArray'] = $inserted_products;
}else{
array_pop($inserted_products);
$_SESSION['myArray'] = $inserted_products;
}
}else{
echo '<div class="error-msg">No products to remove</div>';
}
}
?>
I'm new in php and right now I'm having a problem when storing data in the $_SESSION array. I have an index page that retrieves information from an XML file and displays each product from the XML file in the page each one with a button to add to a cart. When the button is pressed, I send an XMLHttpRequest with the id of the product I want to add to the $_SESSION array.
This is the main page:
function check_avi(id){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var available = this.responseText;
if (available == "True") {
alert("Add to the cart successfully.");
} else {
alert("Sorry, the car is not available now. Please try other cars.");
}
}
};
xhttp.open("GET", "add_delete_session.php?action=add&id="+id, true);
xhttp.send();
In the php I open the xml, retrieve the info and store it into an array, I then copy the information to the $_SESSION[#number of product]
What is happening is that after I add a product, it deletes in the session array the previous products, so each time I'm only having one product in the array and I want to store all of them to show them later in a shopping cart. The php should return a variable to the main page indicating the availability of the product but I'll do that later.
$arra is the array in where I'm storing the values obtained from the XML file corresponding to the product of the Id sent from the main page, like the price or name. $rf is the variable which count the amount of products stored and serve the same function as $_SESSION['g']
This is my PHP:
<?php
session_start();
$id = $_GET[id];
$action = $_GET[action];
if (empty($_SESSION['g'])) {
$_SESSION['g'] = 0;
}
switch($action){
case "add" :
$xmlDoc = new DOMDocument();
$xmlDoc = simplexml_load_file("cars.xml");
for ($e = 0; $e < 10; $e++) {
$cont = 0;
unset($arra);
foreach ($xmlDoc->carrito[$e]->children() as $child) {
$arra[$cont] = $child;
$cont = $cont + 1;
}
if ($arra[0] == $id) {
for ($f = 0; $f < 10; $f++) {
$rf = $_SESSION['g'];
$_SESSION[$rf][$f] = $arra[$f];
}
$_SESSION['g'] = $_SESSION['g'] + 1;
}
}
break;
case "delete":
break;
}
If anyone could help me I'll be so grateful.
Thanks
I think your in your code
1:
if (empty($_SESSION['g'])) {
$_SESSION['g'] = 0;
}
Actually here you haven't even defined the session at all and you are checking for its value if empty or not that's gonna stop execution of your code there itself, first you need to define the session variable and the check the value for it.
2:
$rf = $_SESSION['g'];
$_SESSION[$rf][$f] = $arra[$f];
Because it means that
$_SESSION[$_SESSION['g']][$f] = $arra[$f];
Which is a wrong approach.
Better way first you make all the simplifications and then assign it to the $_SESSION[] and echo it.
Already read some of questions about this problem on stackoverflow and none of that answers apply to me.
When I run:
$item_price = ItemPrice::where('item_name',$itemname)->first();
and then
$item_price->price
I get Trying to get property of non-object but when I run:
dd($item_price = ItemPrice::where('item_name',$itemname)->first());
It's returning object with attributes name, price etc. I don't really understand what is happening here.
Full code:
foreach ($inventorydecoded->assets as $asset) {
$i = 0;
$a = 0;
while ($a < 1) {
if ($inventorydecoded->descriptions[$i]->classid == $asset->classid) {
$a = 1;
$classid = $inventorydecoded->descriptions[$i]->classid;
$itemname = $inventorydecoded->descriptions[$i]->market_hash_name;
$tradable = $inventorydecoded->descriptions[$i]->tradable;
$name_color = $inventorydecoded->descriptions[$i]->name_color;
;
}
$i++;
} // end of while
if ($tradable === 1 && strpos_arr($itemname, $blacklist) == false ) {
$item_price = ItemPrice::whereItemName($itemname)->first();
// dd(ItemPrice::where('item_name',$itemname)->first());
$items[] = ['assetid' => $asset->assetid,'classid'=> $classid,'itemname'=>$itemname,'name_color'=>$name_color,'price'=> $item_price->price];
$serialized_inventory = serialize($items);
}
} // end of foreach
You're using this query in loop, so one of those is empty and returns null. So you need to do simple check:
if (is_null($item_price)) {
// There is no price for this item, do something.
}
Try this:
$item_price = ItemPrice::whereItemName($itemname)->first();
Let me give you the code first and explain below it:
<?php
$productID = $_POST['productID'];
$productAmount = $_POST['productAmount'];
//Declare variables
$cartNumItems = 0;
//Check if cookie exists and set variable if it does
if(isset($_COOKIE['cart'])){
if($_COOKIE['cart'] != null && $_COOKIE['cart'] != ''){
$cart = $_COOKIE['cart'];
}
}
//Get array from cookie
if(isset($cart)){
//Decode array from $cart variable and store it
$cartArray = json_decode($cart);
//Count number of items in $cart
$cartAmount = count($cartArray);
for($i = 0; $i < $cartAmount; $i++){
//Check if $cart has the same product in it already
if($productID == $cartArray[$i][0]){
//Add to the amount of that product
$cartArray[$i][1] += $productAmount;
break;
}
//If it does not have the same product already, just add a new one
else if($i == ($cartAmount - 1)){
array_push($cartArray, array($productID, $productAmount));
break;
};
};
//Recount number of items in $cart
for($i = 0; $i < $cartAmount; $i++){
$cartNumItems += $cartArray[$i][1];
};
//Encode $cart so it can be stored in cookie
$cartRaw = json_encode($cartArray);
//Create cookies
setcookie('cart', $cartRaw, time() + (86400 * 7), '/');
setcookie('cartNumItems', $cartNumItems, time() + (86400 * 7), '/');
echo 'true';
}
else{
//Create the info that needs to be put into cookie
$cart = json_encode(
array(
array($productID, $productAmount)
)
);
$cartArray = json_decode($cart);
//Count and store the amount of items in cart array
$cartAmount = count($cartArray);
//Store amount of items in $cartNumItems variable
for($i = 0; $i < $cartAmount; $i++){
$cartNumItems += $cartArray[$i][1];
};
//Create cookies
setcookie('cart', $cart, time() + (86400 * 7), '/');
setcookie('cartNumItems', $cartNumItems, time() + (86400 * 7), '/');
echo 'true';
};
?>
When this code is ran the very first time, the "cart" cookie is not set. So it runs the big else statement when checking if the variable "$cart" is set. The else statement works fine and does what it's supposed to. It creates a 2d array, then creates the cookies with the needed information.
The second time the code runs, the if statement should run. Which I believe it does. The "cart" cookie (aka "$cart" variable) is set to null. Then the "cartNumItems" cookie (aka "$cartNumItems" variable) is set to 0. Which it's not supposed to do. I just can't find where it does this, or why it does this.
In case there is any confusion about what specifically is the problem code, this is the problem code (it would seem):
//Get array from cookie
if(isset($cart)){
//Decode array from $cart variable and store it
$cartArray = json_decode($cart);
//Count number of items in $cart
$cartAmount = count($cartArray);
for($i = 0; $i < $cartAmount; $i++){
//Check if $cart has the same product in it already
if($productID == $cartArray[$i][0]){
//Add to the amount of that product
$cartArray[$i][1] += $productAmount;
break;
}
//If it does not have the same product already, just add a new one
else if($i == ($cartAmount - 1)){
array_push($cartArray, array($productID, $productAmount));
break;
};
};
//Recount number of items in $cart
for($i = 0; $i < $cartAmount; $i++){
$cartNumItems += $cartArray[$i][1];
};
//Encode $cart so it can be stored in cookie
$cartRaw = json_encode($cartArray);
//Create cookies
setcookie('cart', $cartRaw, time() + (86400 * 7), '/');
setcookie('cartNumItems', $cartNumItems, time() + (86400 * 7), '/');
echo 'true';
}
Update:
I've found what resets the cookie, this bit of code in the if statement:
//Decode array from $cart variable and store it
$cartArray = json_decode($cart);
When this is ran, $cartArray is set to null, therefore the rest of the code is working off of a null variable. Now what I don't understand is why it's being set to null. when I var_dump the $cart variable I get string(16) "[[\"21\",\"1\"]]". But when I run...
echo json_decode($cart);
It just comes out blank.
[[\"21\",\"1\"]] is not valid JSON, because of the \ characters. Those should not be there in the first place – times of magic_quotes_gpc are gone, unless your PHP version was really old. Remove them, before you call json_decode on the string.
So since you say it doesn’t occur locally, but on your web hoster’s server, it very likely is the setting magic_quotes_gpc that is responsible here (if your PHP version is <= 5.3). If your hoster doesn‘t provide any means to turn it of (custom php.ini, .htaccess), then you can use get_magic_quotes_gpc() to detect it from within your script, and then use f.e. stripslashes to remove them.
(Also check the user comments on the manual page for get_magic_quotes_gpc(), they offer solutions to remove those extra slashes from all external input data via a few lines of scripting.)
I am trying to create logic to see what checkbox is selected (of 5 possible checkboxes) and if it is selected assign it a value of 0. if it is not selected I was to assign it a value of 1. The proceeding code snippet highlight this but throws a parse error in my else statement and I cannot fighure out why.
//Check to see what checkbox is marked for correct answer
//Correct answer variables
$chkBox1 = 'unchecked';
$chkBox2 = 'unchecked';
$chkBox3 = 'unchecked';
$chkBox4 = 'unchecked';
$chkBox5 = 'unchecked';
if (isset($_POST['chkBox1'])) {
if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}
else{
$chkBox1 = '1';
}
}//End of chkBox1Selected logic
You don't understand how checkboxes work. If a checkbox is deselected before posting, it will not be set on post.
Therefore, the only condition that will ever be present in your code is that every value will show as 1, since they cannot be overridden.
Take this snippet and try it out. It dynamically loops for the amount of variables you need and assigns the values based upon the submitted value.
$_POST['chkBox4'] = 'test';
for( $i = 1; $i <= 5; $i++ )
{
$name = 'chkBox' . $i;
$$name = !isset( $_POST[$name] ) ? 0 : $_POST[$name];
}
print $chkBox2 . ' // '. $chkBox4;
http://codepad.org/51RotnCf
Ok I got it to work from a syntax standpoint, however now no matter what is selected it is still assigning a value of 1 to all the checkboxes and not changing the selected checkbox to a value of 0. Here is the new code that is correct from a syntax standpoint but defaults to 1 no matter what:
//Check to see what checkbox is marked for correct answer
//Correct answer variables
$chkBox1 = '1';
$chkBox2 = '1';
$chkBox3 = '1';
$chkBox4 = '1';
$chkBox5 = '1';
if (isset($_POST['chkBox1'])) {
if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}
}//End of chkBox1Selected logic
if (isset($_POST['chkBox2'])) {
if ($chkBox2 == 'chkBox2Selected') {
$chkBox2 = '0';
}
}//End of chkBox2Selected logic
if (isset($_POST['chkBox3'])) {
if ($chkBox3 == 'chkBox3Selected') {
$chkBox3 = '0';
}
}//End of chkBox3Selected logic
if (isset($_POST['chkBox4'])) {
if ($chkBox4 == 'chkBox4Selected') {
$chkBox4 = '0';
}
}//End of chkBox4Selected logic
if (isset($_POST['chkBox5'])) {
if ($chkBox5 == 'chkBox5Selected') {
$chkBox5 = '0';
}
}//End of chkBox5Selected logic