0

I started a course on Udemy: PHP for beginners 2023, Build a complete ECommerce store. I've managed to follow everything without any issues, but I have a problem with showing the number of products in cart.

The issue only happens when there are no users logged in. I have absolutely no idea what I'm doing wrong and the course lecturer isn't responding to questions.

I receive the following errors

Notice: Undefined variable: getNumber in C:\xampp\htdocs\bookstore\includes\header.php on line 63

Notice: Trying to get property 'num_products' of non-object in C:\xampp\htdocs\bookstore\includes\header.php on line 63

I'm using XAMPP and MySQL. Code is written on Visual Studio. I added the code below.

Header - Line 63:

<a class="nav-link active  text-white" aria-current="page" href="<?php echo APPURL;?>/shopping/cart.php"><i class="fas fa-shopping-cart"></i>(<?php echo $getNumber->num_products; ?>)</a>

Header - lines 9-13 (this is where I think the error actually is)

if(isset($_SESSION['user_id'])) {
    $number = $conn->query("SELECT COUNT(*) as num_products FROM cart WHERE user_id='$_SESSION[user_id]'");
    $number->execute();

    $getNumber = $number->fetch(PDO::FETCH_OBJ);

}

I was previously directed to the Stack Overflow question below, but I didn't find it helpful. how do i fix the shopping cart number when no users are logged in?

Bear in mind, I am following the course as accurately as possible, so things like query() using execute() is how it is being passed on in the course. $_SESSION['user_id'] is also set. The issue isn't with users logged in, but when nobody is logged in.

I realised I should also point out that the original error was

Notice: Undefined index: user_id in C:\xampp\htdocs\bookstore\includes\header.php on line 11

where line 11

$number = $conn->query("SELECT COUNT(*) AS num_products FROM cart WHERE user_id='$_SESSION[user_id]'");

So, maybe my attempted solution is incorrect?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    `query()` doesn't use `execute()`. Is `$_SESSION['user_id']` set? You should not have values in SQL. Use prepared statements and bind values in via parameterized queries. – user3783243 Feb 27 '23 at 20:21
  • none of my query() commands work without executing. the $_SESSION['user_id'] is set for when a user is logged in, so i have all the data being collected etc. the issue is when there is no user logged in. – Suhail Mahomed Mar 11 '23 at 06:52

0 Answers0