P. Lau
P. Lau

Reputation: 165

PHP print_r($_SESSION) not output what I expect

I have 1st PHP page named session1.php with code below:

<?php
session_start();

.....mysql connection...

$sql = "SELECT name1, brand, price  FROM products WHERE name1='cuvette' ORDER BY 'name1' ASC,'desc1' ASC";
$result = mysqli_query($con,$sql);

while($row = mysqli_fetch_array($result)) {
$_SESSION['tag'] = $row;
print_r($_SESSION['tag']);
}

It outputs:

Array ( [0] => Cuvette [name1] => Cuvette [1] => HmbG [brand] => HmbG [2] => 9.00 [price] => 9.00 ) 
Array ( [0] => Cuvette [name1] => Cuvette [1] => HmbG [brand] => HmbG [2] => 8.00 [price] => 8.00 )

Then I setup 2nd PHP page named session2.php with code below:

<?php
session_start();
print_r($_SESSION['tag']);
?>

But session2.php only ouputts:

Array ( [0] => Cuvette [name1] => Cuvette [1] => HmbG [brand] => HmbG [2] => 8.00 [price] => 8.00 ) 

I am expecting the results should be same with session1.php(2 arrays). Anyone has the explanation for this??

Upvotes: 1

Views: 478

Answers (3)

uhowep
uhowep

Reputation: 11

$_SESSION['tag'] is not an array but a variable.You see two arrays because you run print_r twice.

You can compare the following two codes:

while($row = mysqli_fetch_array($result)) {
    $_SESSION['tag'] = $row;   //This is the assignment of variable
}
print_r($_SESSION['tag']);

And the other is:

while($row = mysqli_fetch_array($result)) {
    $_SESSION['tag'][] = $row;  //This is appending the variable to the array
}
print_r($_SESSION['tag']);

Upvotes: 0

Obsidian Age
Obsidian Age

Reputation: 42304

Your first page is assigning to $_SESSION['tag'] from inside a while loop:

while($row = mysqli_fetch_array($result)) {
  $_SESSION['tag'] = $row;
}

Because you are assigning to a variable, rather than pushing to an array, each time you make the assignment you are overwriting any existing content stored within the session variable.

To resolve this, you can assign an array directly to a $_SESSION variable, such as:

$_SESSION['tag'] = [];
while($row = mysqli_fetch_array($result)) {
  $_SESSION['tag'][] = $row;
}

The output appears to be correct in the first page, because your print statement is within the while loop. The variable is written to, printed out, then overwritten, and printed out again.

Hope this helps! :)

Upvotes: 1

LF-DevJourney
LF-DevJourney

Reputation: 28529

You call the print_r() in the while loop in the first php file, which may be executed many times, and the session value has been oberrided.

Change your code to this, it will be ok.

$_SESSION['tag'] = [];
while($row = mysqli_fetch_array($result)) {
$_SESSION['tag'][] = $row;

}
print_r($_SESSION['tag']);

Upvotes: 1

Related Questions