mysql - PHP Session Array Accessing Another Session

I am stuck in this error for 2 days, please help me out on this.

Detailed Query:

I am able to add the items into the cart using PHP Session but why Another session variable showing in the HTML Table after login.

insert_cart.php

<?php
session_start();
$prod_name= $_POST['prod_name'];
$price= $_POST['price'];
$qty= $_POST['qty'];
$id= $_POST['id'];
$prod_img= $_POST['prod_img'];
$product = array($prod_name,$price,$qty,$id,$prod_img);
$_SESSION[$prod_name] = $product;
//print_r($product);
header('location:view_cart.php');

?>

view_cart.php

<div class="container pt-1 pb-1">
<div class="row">
<div class='table-responsive'>
<table class='table table-condensed table-striped table-hover'>
<thead>
   <tr>
      <th>Product</th>
      <th>Price:</th>
      <th>Quantity</th>
      <th>Total Prices</th>
      <th>Update</th>
      <th>Delete</th>
   </tr>
</thead>
<?php
    $bill= 0;
    $sno = 1;
    //print_r($_SESSION);
   
    foreach($_SESSION as $products){
        //print_r($products);
        echo "<tr>";    
        echo "<form action='edit_cart.php' method='post'>"; 
        if (!$products) $products = array();  
            foreach($products as $key =>$value){
                if($key == 0){   
                    echo "<input type='hidden' name='name$key' class='form-control' value='".$value."'>";       
                    echo "<td>".$value."</td>";   
                } else if($key == 1){  
                    $p = $value;   
                    echo "<input type='hidden' name='name$key' class='form-control' value='".$value."'>";        
                    echo "<td>".$value."</td>";     
      
                }else if($key == 2){  
                    $q = $value;   
                    echo "<td><input type='number' name='name$key' class='form-control col-xl-4 text-center' min='1' value='".$value."'></td>";     
                    $bill = ($p * $q);
                    echo "<td>".($bill)."</td>";
               echo "<td><input type='submit' name='event' value='Update' class='btn btn-sm btn-warning'></td>";
                echo "<td><input type='submit' name='event' value='Delete' class='btn btn-sm btn-danger'></td>";   
            }
        }
   
        echo "</form>"; 
        echo "</tr>"; 
    }
    
   echo "</table>";
   echo "</div>";         
?>

Output in View_Cart.php:

enter image description here

But if I do log in I am getting this error.

and line number 57 is : foreach($products as $key =>$value){

enter image description here

var_dump($products); Output,

Why login_exec.php $_SESSION['SESS_FIRST_NAME'] -> Santhosh Gururaj showing here.

enter image description here login_exec.php

<?php
    session_start();
   
    require_once('connection.php');
    $errmsg_arr = array();
    $errflag = false;
   
   
    $username =$_POST['user_name'];
    $password =$_POST['password'];
   
    if($username == '') {
        $errmsg_arr[] = 'Username missing';
        $errflag = true;
    }
    if($password == '') {
        $errmsg_arr[] = 'Password missing';
        $errflag = true;
    }
   
    //If there are input validations, redirect back to the login form
    if($errflag) {
        $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
        session_write_close();
        header("location:login.php");
        exit();
    }
   
    $sth = $conn->prepare("SELECT * FROM users WHERE email='$username' and password='$password' and status='active'");
    $sth->execute();
    if ($sth->rowCount() >= 1 ) {
        $user = $sth->fetch(PDO::FETCH_ASSOC);
        session_regenerate_id();
        $_SESSION['SESS_MEMBER_ID'] = $user['id'];
        $_SESSION['SESS_FIRST_NAME'] = $user['name'];
        $_SESSION['SESS_LAST_NAME'] = $user['password'];        
        $_SESSION['msg']="You Are Loggedin Succesfully!";  
        session_write_close();
        header("location: view_cart.php");   
        exit();
    }else {
        //Login failed
        $errmsg_arr[] = 'User name and Password not found';
        $errflag = true;
        if($errflag) {
            $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
            session_write_close();
            $_SESSION['msg']="You Are Loggedin Succesfully!";   
            header("location:login.php");
               
            exit();
        }
   }
   {
    die("Query failed");
          
   }
   ?>

Answer

Solution:

During login you're setting $_SESSION['SESS_MEMBER_ID'] and other use data. The errors you see are because you're trying to loop trough these values as well, which aren't arrays, so they can't be looped trough.

A solution would be to add a separate 'products' key to your session in insert_cart.php, e.g.:

<?php
$prod_name = filter_input(INPUT_POST, 'prod_name', FILTER_SANITIZE_STRING);
$something = filter_input(...);

$product = array($prod_name, $something, ...);

$_SESSION['products'][$prod_name] = $product;

Then in view_cart.php you can loop trough the products:

$products = $_SESSION['products'] ? (array)$_SESSION['products'] : [];
foreach($products as $product) {
 // ...
}

Aside from that, please keep in mind: You can never trust user input!

Your current set-up allows me to overwrite the entire session, if I'd post $_POST['prod_name'] = 'SESS_MEMBER_ID';, I could possibly switch to another user, or at least mangle the session.

Hava a look at the filter_input functions for more info. Same goes for way you're using mysqli_prepare, use bind param instead of embedding the variables into the query.

Source