I just ran a simple test with two scripts test1.php and test2.php as shown below:
<?PHP
// test1.php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect("localhost", $username, $password, $database);
if (!$con) die("Connecting to database failed: " . mysqli_connect_error());
$sql = "SELECT * FROM register WHERE id = 1";
if ($result = mysqli_query($con, $sql)) {
$dbrec = mysqli_fetch_array($result,MYSQLI_ASSOC);
if ($dbrec) {
$id = $dbrec['id'];
$username = $dbrec['username'];
echo 'test1 > id ='. $id .' username = '. $username. '<br>';
}
// Go to test2
include 'test2.php';
exit;
} else {
mysqli_free_result($dbrec); // Free result set
mysqli_close($con); // Close the connection
}
?>
<?PHP
// test2.php
echo 'test2 > id ='. $id .' username = '. $username. '<br>';
if (mysqli_close($con)) {
echo 'Database connection successfully closed <br>';
} else {
echo 'Unable to close the Database<br>';
}
?>
I am surprised that this is the output:
test1 > id =1 username = student1 test2 > id =1 username = student1 Database connection successfully closed
From this, my questions:
- For this result I thought I would have needed to use session variables, implementation of which I'm trying to understand. Are the variables defined in test1.php really available to test2.php or do I indeed need to use session variables?
- Does test2.php still have access to the database connection from test1.php or should I have reconnected?