-1

I'm Facing problem in adding variable or row from database into $_SESSION. Here i'm fetch rows from database and storing it into $_SESSION with the help of array. But i'm not able to update/add/delete row quantity in $_SESSION[].

I will be very thankful if you tell me what is the proper way of adding arrays to $_SESSION[] and how to update/delete its particular row only in $_SESSION[]. When i use in_array() it only finds the last row values. when i try to find values of 2nd or 3rd row it says not found.

Note : I have searched in stackoverflow for this question. but those answere not come close to my question. Here are those links below link1 ,link2, link3

Here is my database table :

Table Image

my Output :

Output image

PHP page :

 <?php
    $link = new mysqli('localhost','root','admin','pavancart');
    if ($link->connect_error){
        die("Connection failed: ".$link->connect_error);
    } 

    $sql = "SELECT * FROM  product";
    $res= $link->query($sql);

    while($row = $res->fetch_assoc()){
        $_SESSION['item']=$row;
        echo '<pre>';
            echo print_r ($_SESSION["item"],true);
        echo '</pre>';
    }

    if(in_array("1",$_SESSION['item'])){
        echo "found";
    }else{
        echo "Not found";
    }
?>
Pavan Baddi
  • 479
  • 1
  • 11
  • 22

1 Answers1

1

Your while loop is fine but $_SESSION['item'] is replaced by new row every time so, in_array("1",$_SESSION['item']) statement after the loop always looks in last item fetched by while loop. If you want to check in every row put if ... else statement inside while loop,

if you want to put all records in $_SESSION['item'], you could not accomplish like this, you should first declare $_SESSION['item'] as an array then push each row in it... like-

// declare $_SESSION['item'] as an array
$_SESSION['item'] = [];
while($row = $res->fetch_assoc()){
    // Now push each row in $_SESSION['item']
    // ........... place your if ........ else block here
    array_push($_SESSION['item'],$row);
}

echo '<pre>';
// now you will get $_SESSION["item"] in 2D array
echo print_r ($_SESSION["item"],true);
echo "</pre>";

If you want to make search functionality over 2D array please Read This

Community
  • 1
  • 1
Veshraj Joshi
  • 3,544
  • 3
  • 27
  • 45