I was looking for examples of using global variables in IF statements, found few but I still cannot make my code to work. I'm declaring variable globally and tried to assign values inside if statement and later to check if the variable contains certain value. When I echo the variable, it is not updated with the value I'm assigning within if statement. My code:
<?php
$cart = 0;
if ((isset($_POST["b1"]) && $_POST["b1"] === "Add to cart")) {
global $cart;
$cart = 1;
$query_HOD = "INSERT INTO orderLine
(LINE_ID, PRODUCT_ID, QUANTITY, AMOUNT)
VALUES
('LINE1', '00001', 1, 6.99)";
if ((isset($_POST["add"]) && $_POST["add"] === "Go to cart")) {
echo $cart;
if($cart === 1) {
echo $cart;
header("location:cart.php");
}
else {
echo "<script type='text/javascript'>alert('Your cart is empty');</script>";
}
}
?>
isset methods are working fine, I have checked those, it seems to me that the variable is updated but only locally and does not affect the global variable.
Perhaps you're expecting a global variable to mean a variable that persists between requests; that's not what they are. A global is just a variable that is accessible anywhere in your code for that request . As @user1231958 stated, you'll want a cookie or some other way to persist state.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.