Question

I have a login form for users and admin and i want my users to be greeted by there first name after they login.

i have a table called users with the following columns ID, username, password, admin, fname, lname

i have the login script code as below and would like any help if you guys/gals can offer as i am very new to php

//Connect to db
include("conndb.php");
session_start();
//Get variables from login form
$username = $_POST['username'];
$password = $_POST['password'];
echo $username;
echo $password;
$password = MD5($password);

//query to find if user and password exist and match the password.
$query = "SELECT username, admin FROM users WHERE (username = '$username' AND password      
= '$password')";
$result = mysql_query($query)
or die (mysql_error($connect));

if (mysql_num_rows($result) !=1) {
$_SESSION['loginfail'] = 1;
header ('location: index.php');
}                    

elseif (mysql_num_rows($result) ==1)
{
// check for admin flag

$a = mysql_fetch_array($result);

if ($a[admin] == Y)
{
 $_SESSION['admin'] = 1;
header('location: admin.php');
}
else
{
 $_SESSION['user'] = $fname;
header('location: index2.php');
}

}
Was it helpful?

Solution

Change this to

if ($a[admin] == Y)
{
    $_SESSION['admin'] = 1;
    $_SESSION['username'] = $a['username'];
    header('location: admin.php');
}
else
{
   $_SESSION['user'] = 1;
   $_SESSION['username'] = $a['username'];
   header('location: index2.php');
}

Now use this $_SESSION['username'] to show user name on your web page.

OTHER TIPS

you need to save the username or id into the session ($_SESSION) and in admin.php and index2.php you need to query the fname of the user and use it accoridingly

You might not have started session. So start your session by adding the following line at the top of the page.

session_start();

Moreover change last part of the code as follows:

$_SESSION['username'] = $a['username'];
if ($a['admin'] == 'Y') {
     $_SESSION['admin'] = true;
     header('location: admin.php');
}else{
     $_SESSION['user'] = true;
     header('location: index2.php');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top