Sam Irving
Sam Irving

Reputation: 21

Setting a Session Variable

Wonder if someone could help me. I am trying to set a session variable from a database table. Essentially what I need to do is when someone logs in, it takes the value from the 'user_group' column of the user table for the user that has logged in and assign it to the session variable. At the moment it is just passing in the username which is manually typed in by the user upon login.

This is my current code for login.php. I have tried various things and looked on here for tips but haven't had any luck.

<?php

session_start();

$host = "localhost";
$user = "root";
$pass = "";
$db = "california";

mysql_connect($host, $user, $pass);
mysql_select_db($db);


	$username = $_POST['name'];
	$password = md5 ($_POST['password']);
	// check to make sure both fields are entered
 if ($username == '' || $password == '')
 {
 header("Location:login-fail.htm");
 }
 else
	$sql = "SELECT * FROM users WHERE name='".$username."' AND password='".$password.
	"' LIMIT 1";
	$res = mysql_query($sql);
	if (mysql_num_rows($res) == 1) {
	    $_SESSION['logged_in']= $username;
		header("Location:login-success.htm");
		exit();
	} else {
		header("Location:login-fail.htm");
		exit();
	}

?>

Upvotes: 2

Views: 4542

Answers (2)

M&#225;rio Kapusta
M&#225;rio Kapusta

Reputation: 508

You have to use result from db:

//...
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
    $_SESSION['logged_in']= $row['user_group'];
}
//...

EDIT: Try to use Mysql PDO instead of mysql_* functions. They are deprecated: http://php.net/manual/en/ref.pdo-mysql.php

Upvotes: 0

mirko911
mirko911

Reputation: 353

what happens if you add a

$row = mysql_fetch_assoc($res);

after you mysql_query and assign the group to the session

$_SESSION['logged_in'] = $row['user_group']

EDIT: I also want to inform you that mysql_* functions are deprecated. Also your mysql query isn't protected against SQL Injections

Upvotes: 3

Related Questions