0

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:

  1. 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?
  2. Does test2.php still have access to the database connection from test1.php or should I have reconnected?
bmuu
  • 17
  • 1
  • 6
  • 1
    You included code, you didn't redirect to a new page. "The include expression includes and evaluates the specified file." It's as if you just joined the two files. That make sense? – ficuscr Feb 23 '22 at 00:49
  • Oh I see @ficuscr, and now that makes sense and therefore there was no need to mysqli_close($con) in test2.php So there is another way to execute test2 that would require db reconnection and session variables!!! – bmuu Feb 23 '22 at 00:57
  • 1
    You could do a redirect. See `location` header. [How do I make a redirect in PHP?](https://stackoverflow.com/questions/768431/how-do-i-make-a-redirect-in-php) – ficuscr Feb 23 '22 at 01:03
  • 1
    I thought I'd replied before....Thank you @ficuscr – bmuu Feb 25 '22 at 23:42

0 Answers0