I will describe my problem in two parts (previous problem and current problem).
Previous Problem:
Initially, on page3.php
, I wasn't able to retrieve the username using the session variable and hiding //require('../myDBFolder/db.php');
solved the problem and I was able to see the username on that page.
Current Problem:
Since, I have commented out the line //require('../myDBFolder/db.php');
, I am not able to access the other variables defined in db.php
like $connection
variable and hence I am trying to figure out how to make sure I have $connection
variable available in page3.php
.
A Quick explanation of the working of files is in the following order:
User submits username from page1.html
, page2.php
does the authorization work with db.php
as required file and upon successful authorization, it directs the user to page3.php
.
Please consider my files below:
page1.html
<form method="post" action= "page2.php" name="lform">
<span class="style1">User Name :</span>
<input type="text" name="user" size="25">
<input type="submit" value="login">
</form>
db.php
<?php
session_start();
$user = $_POST["user"];
$_SESSION['username']=$user;
$db_server = "localhost";
$db_name = "PracticeDB";
$db_user = $user;
$table_name_data = "collegestudents";
$connection = mysqli_connect($db_server,$db_user,$db_password) or trigger_error("Could Not Connect to the Database : ". mysqli_connect_error(), E_USER_ERROR);
$db = mysqli_select_db($connection , $db_name) or trigger_error("Could Not Select the Database : " . $db_name . ':' .mysqli_error($connection));
?>
page2.php
<?php
session_start();
require('../myDBFolder/db.php');
$user = $_POST["user"];
$_SESSION['username'] = $user;
$sql="SELECT * FROM $table_name_users WHERE username = \"$user\"";
$result=mysqli_query($connection,$sql) or trigger_error("Couldn't Execute Query in page2.php: ". mysqli_error($sql));
$num = mysqli_num_rows($result);
if ($num != 0) {
print "<script>";
print "self.location='page3.php';";
print "</script>";
} else {
echo "<p>you're not authorized";
}
?>
page3.php
<?php
session_start();
//require('../myDBFolder/db.php');
$user = $_SESSION['username'];
$sql = "SELECT * FROM $table_name_data WHERE username = '$user'";
$result = mysqli_query($connection,$sql) or trigger_error("Could Not Execute the Query ! : ". mysqli_error($connection));
?>
Troubleshooting Steps:
1) I have tried to include require('../myDBFolder/db.php');
in page3.php
file and it solves the problem of $connection
parameter but I don't see username coming onto that page via session for some reason and also by including //require('../myDBFolder/db.php');
in page3.php
I will be making db connection twice as I have already done that in page2.php
and haven't closed it.
2) Another thing, I was looking at some of the threads discussed before like this one, it seems like storing $connection
in a session variable is not a good idea.