I have 2 files login.php
and employee.php
.
When I log in to the website, I create a connection to my database. How can keep that connection so that I can call some query statement in employee.php
file?
This is login.php
:
<?php
if (isset($_POST["login"])) {
$server_name = "my-server.database.windows.net";
$user_name = $_POST['user_email'];
$password = $_POST['user_password'];
$connection = array("Database"=>"BankingDB", "UID"=>$user_name, "PWD"=>$password);
$conn = sqlsrv_connect($server_name, $connection);
if ($conn) {
session_start();
$_SESSION['user_name'] = $user_name;
$_SESSION['password'] = $password;
setcookie("type", $user_name, time() + 3600);
header("location:index.php?page=employee");
}
else {
echo "<div class='alert alert-danger'>Wrong Email Address or Password!</div>";
die(print_r(sqlsrv_errors(), true));
}
}
?>
This is employee.php
:
<?php
session_start();
$server_name = "my-server.database.windows.net";
$connection = array("Database"=>"BankingDB", "UID"=>$_SESSION['user_name'], "PWD"=>$_SESSION['password']);
$conn = sqlsrv_connect($server_name, $connection);
if ($conn) {
echo "Connection established: " . $server_name;
}
else {
echo "Connection could not be established";
die(print_r(sqlsrv_errors(), true));
}
$id = $_GET['employee_id'];
$sql = "SELECT EmployeeName, EmployeeCode FROM Employee WHERE EmployeeCode = $id;";
$query = sqlsrv_query($conn, $sql);
$row = sqlsrv_fetch_array($query);
?>
I can save the user_name
and password
with $_SESSION
variable. I also have many files that also use this connection.
I did try to store the $conn
in $_SESSION
but it doesn't work.
<?php
// login.php
$conn = sqlsrv_connect($server_name, $connection);
$_SESSION['connection'] = $conn;
?>
How can I keep that connection so that I don't have to reconnect to the database every time I need to query?