David
David

Reputation: 23

How to pass the username by using session function

<?php
session_start();
error_reporting(E_ALL ^ E_DEPRECATED);
$host = "localhost";
$user = "root";
$pass = "";
$db = "testing";
mysql_connect($host, $user, $pass);
mysql_select_db($db);
if (isset($_POST['loginID'])) {
    $loginID = $_POST['loginID'];
    $password = $_POST['password'];
    $sql = "SELECT * FROM user WHERE loginID='".$loginID."' AND password='".$password."' LIMIT 1";
    $res = mysql_query($sql);
    if (mysql_num_rows($res) == 1) {
        header("Location:homepage.php");
        $_SESSION['loginID'] = $loginID;
    } else {
        header("Location:login.php");die;
    }
}
?>

I want to pass the username in a session, to show the username in homepage.php, but it didn't work when I tried to do so. What is wrong, and how can I make it work?

Upvotes: 1

Views: 92

Answers (3)

jeroen
jeroen

Reputation: 91792

You need to fetch a row from your result set and use information from that row for your session variable:

$res = mysql_query($sql);
if ($row = mysql_fetch_assoc($res)) {
    $_SESSION['loginID'] = $loginID;
    $_SESSION['name'] = $row['username'];    // or whatever the column is called where the username is stored
    header("Location:homepage.php");
    exit();
} else {
    header("Location:login.php");die;
}

Apart from that a few comments:

  • You should switch to PDO or mysqli using prepared statements. The mysql_* functions are deprecated and you have an sql injection problem now;
  • You should never store plain-text (or encrypted...) passwords. Passwords should be salted and hashed, see Secure hash and salt for PHP passwords

Upvotes: 0

SonaliM
SonaliM

Reputation: 1

session value should be stored first and then redirect to another page. Try following: if(mysql_num_rows($res)==1) { $_SESSION['loginID']=$loginID; header("Location:homepage.php"); }

Upvotes: 0

WillardSolutions
WillardSolutions

Reputation: 2314

Change this:

if(mysql_num_rows($res)==1)
{
header("Location:homepage.php");
$_SESSION['loginID']=$loginID;
}

to this:

if(mysql_num_rows($res)==1)
{
$_SESSION['loginID']=$loginID;
header("Location:homepage.php");
}

Upvotes: 1

Related Questions