Hello,
I have a client that wants his users to be redirected upon login to a page that displays only information that pertains to this user. Kind of like a bank site that only shows their account.
I need to know
1. How to do that type of redirect
2. How to pull user specific info form database.

Thanks,
Tim

Recommended Answers

All 29 Replies

I'm assuming that if you want to pull user specific info from the database that this is a member's site where users need to log in? In your login script, once you have verified username, email, password, whatever ... you can use header to redirect. eg.

{ ... validate user here ... 
header("Location: myaccount.php");
		}
		else
		{
		$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
		header("Location: login.php?msg=$msg");
		}

That's just a snippet, but what it does is bounce the user to their "myaccount" page if login is successful, or keeps them at the login page and shows and error message if it is not successful.

Once the user is logged in chances are that you are tracking some sort of info through a session, it could be anything, but lets say it's a user id #. Assuming you have info in the database for that user, just use their session info (id # in this case) to query the database and extract the info on that user. Here's an example:

$sql = "SELECT * FROM users WHERE user_id = '$_SESSION[user_id]' ";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)){
$fn = $row['first_name'];
$ln = $row['last_name']; } 

echo " Welcome to your account ".$fn." ".$ln." ";

You can pull whatever info you want out of the database for that user assuming the info is there to begin with. It's a little vague, but I hope it helps at least a little. Let us know if you need something clarified.

Ecellent, I will give that a try after the weekend and let you know how it works out.
Thank you

No I guess I am further off than I thought.
I can start a session, but I am not sure how to store say the "usename" inputted though a form, and then retieve it on the next page and say something like: Welcome "username".
Then from there is where I want to pull that users information from the database.
I am using Dreamweaver CS4, but the way they suggest to do it does not show any output then I use the recordset feature.

Member Avatar for diafol

Login systems typically use sessions. A simple version following submission of a login form would validate the data then verify then (if successful), place the user's id into a $_SESSION variable (or similar). This is then used to reference the user's data in db calls. With this there is no need to have a querystring. However, this isn't the most secure way of doing things, but it's ok for now. Read up on sessions and secure session data for more info.

For this you need to put

session_start();

at the head of every php page.

Here's an example:

$user_id = $_SESSION['user']['id'];
$rs = mysql_query("SELECT * FROM user WHERE id='$user_id'");
...etc...

Here is a general idea of how I set a session and assign sessions variables. I'm rather new to this myself, so bear with me. Other member's here are Aces at this.

Anyhow, this script comes from a login page.

$sql = "SELECT `id`,`user_name`,`approved`, `expire_date`, `user_email`, `zip` FROM users WHERE 
           $user_cond
			AND `pwd` = '$md5pass' AND `banned` = '0' ";
 			
$result = mysql_query($sql) or die (mysql_error()); 
$num = mysql_num_rows($result);
list($id,$user_name,$approved,$exp,$user_email,$zip) = mysql_fetch_row($result);

I use the query ($sql) to authenticate the users as well as pull info from the database that will be used as session variables.

Then I set the variables for the session (only if the user has been authenticated):

session_start(); 
	   // this sets variables in the session 
		$_SESSION['user_id']= $id;  
		$_SESSION['user_name'] = $user_name;
		$_SESSION['expire_date'] = $exp;
		$_SESSION['user_email'] = $user_email;
		$_SESSION['zip'] = $zip;

When the users lands on whatever page your direct them to upon successful login, the page could disply

echo "Welcome ".$user_name." "; 
// OR
echo " Welcome ".$_SESSION['user_name']." ";

Hope that helped a little.

Ok, Im making progress. I have the login part working and set a sesssion variable for "username" that shows the users name on the next page after logged in.
Now the part I can't figure out is how to pull info from the database for that user based on the username variable.
I have a database named "users" with a table called "user".
How would I pull say the users first and last name (fname, laname colums in database)?

Thanks for all the help, you all rock!

Try this out.

$sql = " SELECT * FROM user WHERE user_name = '$user_name' ";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)) {
$fn=$row['fname'];
$ln=$row['laname']; }

echo " Welcome ".$fn." ".$ln." ";

When I assign my session variables I like to set the user ID as well. This will help avoid any confusion or mix ups with members that have similar names or user names, eg. Bob Smith. This way you can just query > WHERE id = '$user_id' ";

I used that code and get this error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /hermes/web06/b90/as.bobdonovan/public_html/new/login_success.php on line 27
Line 27 contains this : while($row=mysql_fetch_array($result)) {

You need to replace user_name = '$user_name' with the correct column name in the table where you store the user name, and also make sure that the variable for $user_name is correct.

What is the column name for user name? And what is the variable you are assigning to it ?

Got it! Yes!!!
Thanks a lot everyone!

Glad it worked out for ya' !

Well I thought it was working. Problem is, it was pulling only first record from database, no matter who I log in. I thought it was an issue with that record so I deleted it from DB. Now nothing happens again.
Here is my code from my login_success.php. Maybe you can see something.
Databae is called users. Table called user. Goal is to extract user info from username session variable.

Code:

<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);

  $logoutGoTo = "index.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?php
session_start(); 
?>      
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>

<body>
<p>
Welcome Back
<?php echo $_SESSION['MM_Username']; ?>
</p>
<p>
  <?php 
$link = mysql_connect(hidden, 'hidden', 'hidden); 
if (!$link) { 
    die('Could not connect: ' . mysql_error()); 
} 
echo 'Connected successfully'; 
mysql_select_db(users); 

$sql = " SELECT * FROM user WHERE username = '$MM_username' ";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)) {
$fn=$row['fname'];
$ln=$row['laname']; }

echo " Welcome ".$fn." ".$ln." ";
?>
  </p>
<p><a href="<?php echo $logoutAction ?>">Log out</a></p>
</body>
</html>

First make sure there is actually a record in the database (you said you deleted it). If so, try this out.

$sql = " SELECT * FROM user WHERE username = '$_SESSION[MM_username]' ";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)) {
$fn=$row['fname'];
$ln=$row['laname']; }

echo " Welcome ".$fn." ".$ln." ";

If you assigned a variable to a session variable, ex. $user_name = "".$_SESSION['MM_username'].""; you can use $user_name in your query instead ... if not you have to use $_SESSION .. ..

I didnt delete all of the database. I still have 2 test users.
That code still didnt work. Mabye its how I assigned the session variable. This is the code:
$_SESSION = $loginUsername;
I did that with dreamweaver CE4. It created that code when I made a log in form.

When you say it didn't work is it giving you an error or just still returning the first record?

It was just returning the first record, which ironically wasn't assigned a username. Once I deleted the first record it stopped returning info at all. No errors.

Try to echo $MM_username and see what value it's holding, if any. That will help narrow down the problem. echo " user name = ".$MM_username.""; die(); Put that as your very next statement after your query.

It just says username=
No result returned. I dont get it.

Well you're variable is definitely empty, that explains why you aren't getting any results. Since it's a session variable you'll need to make sure that you are setting the session and assigning the variable correctly. It worked before but doesn't now so you dropped something along the way with whatever changes you have made. I'm assuming you are setting the sessions variables on your login page so that is where I would start. Copy and paste that part of the code from your login page and we can have a look at it.

Heres the code for the entire log in page:
<?php require_once('Connections/Users.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
?>
<?php
// *** Validate request to login to this site.
if (!isset($_SESSION)) {
session_start();
}

$loginFormAction = $_SERVER;
if (isset($_GET)) {
$_SESSION = $_GET;
}

if (isset($_POST)) {
$loginUsername=$_POST;
$password=$_POST;
$MM_fldUserAuthorization = "";
$MM_redirectLoginSuccess = "login_success.php";
$MM_redirectLoginFailed = "login.php";
$MM_redirecttoReferrer = false;
mysql_select_db($database_Users, $Users);

$LoginRS__query=sprintf("SELECT username, pass FROM `user` WHERE username=%s AND pass=%s",
GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text"));

$LoginRS = mysql_query($LoginRS__query, $Users) or die(mysql_error());
$loginFoundUser = mysql_num_rows($LoginRS);
if ($loginFoundUser) {
$loginStrGroup = "";


$_SESSION = $loginUsername;
$_SESSION = $loginStrGroup;

if (isset($_SESSION) && false) {
$MM_redirectLoginSuccess = $_SESSION;
}
header("Location: " . $MM_redirectLoginSuccess );
}
else {
header("Location: ". $MM_redirectLoginFailed );
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<form ACTION="<?php echo $loginFormAction; ?>" id="loginform" name="loginform" method="POST">
<p>
<label>Username
<input type="text" name="username" id="username" />
</label>
</p>
<p>
<label>Password
<input type="password" name="password" id="password" />
</label>
</p>
<p>
<label>
<input type="submit" name="submit" id="submit" value="Submit" />
</label>
</p>
</form>
</body>
</html>

Everything seems to be in order with your login. Make sure that you declare the session_start(); at the top of the page (before the <html> tag) on your pages. If you didn't write the script yourself and you don't see it somewhere near the top of the page, chances are that is being called through an include such as config.php or something of the sort. You'll want to check to make sure it is in place. For now, on your login success page paste this into the code just before your query where you are pulling the $fn and $ln from the databse. echo "".$_SESSION['MM_Username']."";die(); log in again and see what it gives you.

That returns the session username, so I know the session is working, its the pulling from the database thats driving me nuts.

Kkeith29, That script looks great, its just that I need to user to only get their own info from the database after login. Thank you though, I may use that in the future for something else.

It seems to me that as long as there is a matching username in the database, one of the following should do the trick for you.

$sql = " SELECT * FROM user WHERE username = '$_SESSION[MM_username]' ";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)) {
$fn=$row['fname'];
$ln=$row['laname']; }
 
echo " Welcome ".$fn." ".$ln." ";

// OR 

$user_name = $_SESSION['MM_username'] ; 

$sql = " SELECT * FROM user WHERE username = '$user_name' ";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)) {
$fn=$row['fname'];
$ln=$row['laname']; }
 
echo " Welcome ".$fn." ".$ln." ";

Still not working :(
Heres how the code looks after your suggestion:
<?php require_once('Connections/Users.php'); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
session_start();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>

<body>

Welcome Back
<?php echo $_SESSION; ?>
<?php
$link = mysql_connect(hidden', 'hidden', 'hidden');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(users);

$sql = " SELECT * FROM user WHERE username = '$_SESSION[MM_username]' ";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)) {
$fn=$row;
$ln=$row; }

echo " Welcome ".$fn." ".$ln." ";
?>
</body>
</html>

Is it possible that its the way I am storing in the database? I dont get it. I just looked and I do have 3 users in this test base. Each one has id,fname,laname,username,password,email.
We know that the script is connecting to the DB, so its the pulling thats an issue. I know its something small I am missing.

Replace the first line of your query with this :

$sql = " SELECT * FROM user WHERE username = '$_SESSION[MM_Username]' ";

That was it. Good eye!!! Now I can add the rest to that script.
Thanks a million.

Sure thing. Sorry we had to go around the block just to get across the street. Should've caught that sooner.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.