I am using sessions to pass user information from one page to another. However, I think I may be using the wrong concept for my particular need. Here is what I’m trying to do:
- When a user logs in, the form action is sent to login.php, which I’ve provided below:
login.php
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$con = mysql_connect("xxxx","database","pass");
if (!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
session_start();
$_SESSION['loggedin'] = 1; // store session data
$_SESSION['loginemail'] = fldEmail;
header("Location: main.php"); }
}
mysql_close($con);
- Now to use the $_SESSION[‘loggedin’] throughout the website for pages that require authorization, I made an ‘auth.php’, which will check if the user is logged in.
The ‘auth.php’ is provided below:
session_start();
if($_SESSION['loggedin'] != 1){
header("Location: index.php"); }
-
Now the point is, when you log in, you are directed BY login.php TO main.php via header. How can I echo out the user’s fullname which is stored in ‘fldFullName’ column in MySQL on main.php? Will I have to connect again just like I did in login.php? or is there another way I can simply echo out the user’s name from the MySQL table? This is what I’m trying to do in main.php as of now, but the user’s name does not come up:
$result = mysql_query("SELECT * FROM Members WHERE fldEmail='$loginemail' and Password='$loginpassword'"); //check if successful if($result){ if(mysql_num_rows($result) == 1){ $row = mysql_fetch_array($result); echo '<span class="backgroundcolor">' . $row['fldFullName'] . '</span><br />' ;
Yes. This is the way PHP and mysql works
No. To get something from mysql table you have to connect first.
You can put connect statement into some config file and include it into all your scripts.
You will need some identifier to get proper row from database. email may work but it’s strongly recommended to use autoincrement id field instead, which to be stored in the session.
And at this moment you don’t have no $loginemail nor $loginpassword in your latter code snippet, do you?
And some notes on your code
any
header("Location: ");statement must be followed byexit;. Or there would be no protection at all.Any data you’re going to put into query in quotes, must be escaped with
mysql_real_escape_string()function. No exceptions.so, it going to be like this
and main.php part