0

I script it as follows,

session_start();
$employees = null;

if (isset($_SESSION['employees'])) {
    $employees= $_SESSION['employees'];

} else {

$con = new mysqli("localhost", "root", "test", "emp_db");
$employees = $con->query("SELECT * from employee");
$_SESSION['employees'] = $employees;
}

echo "<table>";

foreach ($employees as $row) {
   echo '<tr>';
   echo "<td>" . $row['emp_id'] . " </td>";
   echo "<td>" . $row['emp_name'] . " </td>";
   echo "<td>" . $row['emp_address'] . "</td>";
   echo "</tr>";
}

The first page access goes well, i.e. accessing from db. But when I try to fetch from $_SESSION in 2nd page request, it says ...

"Warning: main(): Couldn't fetch mysqli_result in C:\xampp\htdocs\test\dbtemp.php on line 22". My line 22 is: foreach( $employees as $row) {

Any idea?

If resultset returned by php is connected resource (like Java), why we can still iterate it after closing the connection with DB?

When I call get_resource_type($employees) ... it says, its an object, not a resource. Then why an object is not being stored in session?

Ankur
  • 5,086
  • 19
  • 37
  • 62
Asif Shahzad
  • 843
  • 2
  • 11
  • 21

2 Answers2

3

Quoted from SO question Storing database connection in a session variable

You can't store database connections or result sets in the session, since those are resources, and:

Some types of data can not be serialized thus stored in sessions. It includes resource variables or objects with circular references (i.e. objects which passes a reference to itself to another object).

http://php.net/manual/en/intro.session.php

You can extract a result set into a normal array and store that in the session like any other variable. That would be a fairly typical use case for sessions anyway. Just be careful not to store too much data in the session, as that can become more taxing than fetching it from the database.

Community
  • 1
  • 1
STT LCU
  • 4,348
  • 4
  • 29
  • 47
0

Try replace:

$_SESSION['employees'] = $employees;

With:

$_SESSION['employees'] = $employees->fetch_all();

Result set is not shared for scripts, which called with different time. In other words, you cannot properly save active mysqli_result in $_SESSION and use it after database connection was closed. However you can save array. mysqli_result::fetch_all() is what you needed.

Still, I don't think it's a good way. I recommend you to oversee your script.

BlitZ
  • 12,038
  • 3
  • 49
  • 68