Hi Guys,

im creating a shopping cart as part of my website
however whenever i try to empty my cart i get the error: ( ! ) Notice: Undefined index: login_user in C:\wamp\www\catalogue.php on line 32
login_user refers to a session that gets created when the user logs in.

Line 32 looks like this: <?php echo "Welcome ".$_SESSION['login_user'];?>! <br> <a href="logout.php">Logout</a>

its a little weird as to why the error occurs when i click empty cart but points towards the line above

the two files in question are login.php and catalogue.php both are below:

**Login.php:
**

`<?php

session_start(); // Starting Session
include_once('config.php');

$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$_SESSION['login_user']=$user;
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
    $user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$query = mysqli_query($mysqli, "SELECT * FROM users where Username='$user' AND Password='$pass'");
$rows = mysqli_num_rows($query);
if ($rows == 1) {
header("location: home.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css"> 
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>

</head>
<body>

<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span> 
</div>

<div id="login">
  <div id="triangle"></div>
  <h1>Log in</h1>
  <form action = "" id = "logregform" method = "POST">
    <p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
    <input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
    <input type="password" placeholder="Password" name = "pass" required/>
    <input type="submit" value="Log in" name = "submit" />
    <br>
    <br>
    <p id ="bklg">Dont have an account? <a href="register.php">Sign up</a></p> 
  </form>
</div>
<script>

$('#toggle-login').click(function(){
  $('#login').slideToggle('fast'); 
});
</script>
</html>`

**and catalogue.php is:
**

<?php 
error_reporting(E_ALL); 
ini_set('display_errors', 1);
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
</head>
<body>

<br>
<div id="books-wrapper">

<!-- #content to center the menu -->
<div id="content">
    <!-- This is the actual menu --> 
    <ul id="darkmenu">
          <li><a href="home.php">Home</a></li>
          <li><a href="catalogue.php">Catalogue</a></li>
          <li><a href="search.php">Search</a></li>
          <li><a href= "view_cart.php">Cart</a></li>
          <li><a href="#">Orders</a></li>
    </ul>    

<div id = "welcome" >
<?php echo "Welcome ".$_SESSION['login_user'];?>! <br> <a href="logout.php">Logout</a>
</div>
</div>

<br><br>
    <h1 id = "mainHeader" >Books</h1>
<br>   
   <div class="books">
    <?php
    //current URL of the Page. cart_update.php redirects back to this URL
    $current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);

$results = $mysqli->query("SELECT * FROM books ORDER BY Category ASC");
if ($results) { 

    //fetch results set as object and output HTML
    while($obj = $results->fetch_object())
    {
        echo '<div class="book">'; 
        echo '<form method="post" id = "books" action="cart_update.php">';
        echo '<div class="book-thumb"><img src="images/'.$obj->BookImage.'"></div>';
        echo '<div class="book-content"><h3>'.$obj->Title.'</h3>';
        echo '<br>';
        echo '<div class="book-author"><i>'.$obj->BookAuthor.'</i></div>';
        echo '<div class="book-desc">'.$obj->BookDesc.'</div>';
        echo '<br>';
        echo '<div class="book-qty"> In stock: '.$obj->Quantity.'</div>';
        echo '<div class="book-info">';
        echo 'Price '.$currency.$obj->Price.' | ';
        echo 'quantity <input type="text" name="Quantity" value="1" size="3" />';
        echo '<button class="add_to_cart">Add To Cart</button>';
        echo '</div></div>';
        echo '<input type="hidden" name="ISBN" value="'.$obj->ISBN.'" />';
        echo '<input type="hidden" name="type" value="add" />';
        echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
        echo '</form>';
        echo '</div>';
    }
}
?>
</div>


<div class="shopping-cart">
<h2>Your Shopping Cart</h2>
<?php
if(isset($_SESSION["books"]))
{
    $total = 0;
    echo '<ol>';
    foreach ($_SESSION["books"] as $cart_itm)
    {
        echo '<li class="cart-itm">';
            echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["ISBN"].'&return_url='.$current_url.'">&times;</a></span>';
        echo '<h3>'.$cart_itm["Title"].'</h3>';
        echo '<div class="p-ISBN">ISBN : '.$cart_itm["ISBN"].'</div>';
    echo '<div class="p-quantity">Quantity : '.$cart_itm["quantity"].'</div>';
    echo '<div class="p-Price">Price :'.$currency.$cart_itm["Price"].'</div>';
    echo '</li>';
    $subtotal = ($cart_itm["Price"]*$cart_itm["quantity"]);
    $total = ($total + $subtotal);
}
echo '</ol>';
echo '<span class="check-out-txt"><strong>Total : '.$currency.$total.'</strong> <a href="view_cart.php">Go to checkout</a></span>';
echo '<span class="empty-cart"><a href="cart_update.php?emptycart=1&return_url='.$current_url.'">Empty Cart</a></span>';
}else{
    echo 'Your Cart is empty';
}
?>
    </div>

</div>

</body>
</html>

Any idea as to why im getting that error?

Thanks!

What is happening in cart_update.php in order to empty the cart? I suspect the login session is being destroyed in cart_update.php, and thus it cant find "login_user" because the session no longer exists and thus it is "undefined"...

The code for cart update below:

<?php
session_start();
include_once("config.php");

//empty cart by distroying current session
if(isset($_GET["emptycart"]) && $_GET["emptycart"]==1)
{
    $return_url = base64_decode($_GET["return_url"]); //return url
    session_destroy();
    header('Location:'.$return_url);
}

//add item in shopping cart
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
$ISBN   = filter_var($_POST["ISBN"], FILTER_SANITIZE_STRING); //product code
$Quantity   = filter_var($_POST["Quantity"], FILTER_SANITIZE_NUMBER_INT); //product code
$return_url     = base64_decode($_POST["return_url"]); //return url

//limit quantity for single product
if($Quantity > 10){
    die('<div align="center">Not allowed more than 10 quantity!<br /><a href="index.php">Back To Catalogue</a>.</div>');
}

//MySqli query - get details of item from db using product codename
$results = $mysqli->query("SELECT Title,Price FROM books WHERE ISBN='$ISBN' LIMIT 1");
$obj = $results->fetch_object();

if ($results) { //we have the product info 

    //prepare array for the session variable
    $new_product = array(array('Title'=>$obj->Title, 'ISBN'=>$ISBN, 'quantity'=>$Quantity, 'Price'=>$obj->Price));

    if(isset($_SESSION["books"])) //if we have the session
    {
        $found = false; //set found item to false

        foreach ($_SESSION["books"] as $cart_itm) //loop through session array
        {
            if($cart_itm["ISBN"] == $ISBN){ //the item exist in array

                $product[] = array('Title'=>$cart_itm["Title"], 'ISBN'=>$cart_itm["ISBN"], 'quantity'=>$Quantity, 'Price'=>$cart_itm["Price"]);
                $found = true;
            }else{
                //item doesn't exist in the list, just retrive old info and prepare array for session var
                $product[] = array('Title'=>$cart_itm["Title"], 'ISBN'=>$cart_itm["ISBN"], 'quantity'=>$cart_itm["quantity"], 'Price'=>$cart_itm["Price"]);
            }
        }

        if($found == false) //we didn't find item in array
        {
            //add new user item in array
            $_SESSION["books"] = array_merge($product, $new_product);
        }else{
            //found user item in array list, and increased the quantity
            $_SESSION["books"] = $product;
        }

    }else{
        //create a new session var if does not exist
        $_SESSION["books"] = $new_product;
    }
}
//redirect back to original page
header('Location:'.$return_url);
}

//remove item from shopping cart
    if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["books"]))
{
    $ISBN = $_GET["removep"]; //get the product code to remove
        $return_url = base64_decode($_GET["return_url"]); //get return url


foreach ($_SESSION["books"] as $cart_itm) //loop through session array var
{
    if($cart_itm["ISBN"]!=$ISBN){ //item does not exist in the list
        $product[] = array('Title'=>$cart_itm["Title"], 'ISBN'=>$cart_itm["ISBN"], 'quantity'=>$cart_itm["quantity"], 'Price'=>$cart_itm["Price"]);
    }

    //create a new product list for cart
    $_SESSION["books"] = $product;
}

//redirect back to original page
header('Location:'.$return_url);
}
?>

Thanks!

Exactly as I suspected. Your script is destroying the user session on line 9, so when you redirect back to catalogue.php it creates a new session on line 4 for which $_SESSION['login_user'] is not set. This then throws the error on line 32.

You are effectively logging the user out as well as emptying the cart.

Why dont you clear the $_SESSION["books"] array on line 9 instead of destroying the entire session?

Ah i used unset($_SESSION['books']); and it seems to have gotten rid of the error!
Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.