[SOLVED] Session data problem

This is a discussion on "[SOLVED] Session data problem" within the PHP Forum section. This forum, and the thread "[SOLVED] Session data problem are both part of the Program Your Website category.



 Subscribe in a reader

Go Back   Webforumz.com > Main Forums > Program Your Website > PHP Forum

Notices


Reply
 
LinkBack Thread Tools
  #1  
Old Dec 8th, 2007, 16:35
Reputable Member
Join Date: Oct 2007
Location: Liverpool UK
Age: 29
Posts: 217
Thanks: 0
Thanked 0 Times in 0 Posts
[SOLVED] Session data problem

Hello all!

I have created a php page called your_account.php ! Now once the registered user logs in successfully they are transfered to the page mentioned above & there data information is automatically loaded from the database into the your_account page! Now everythink is working fine the data is loading into the page fine, the problem i have is the persons data who registered first seems to load even when anouher user logs in with a diffrent password & username! So no matter which registered user logs in, the same user data loads.

The data that continuesly loads no matter who loags in is the first persons data who registered on the site! Very confusing

.................................................. .................................................. .......

I have used session code found below and i have a feeling that if a seesion starts when someone logs in, the session is meant to terminate once they leave the site, i think my code is possibly incomplete, could anyone offer any advice??

Cheers..

Below is the session code:

PHP: Select all

// check if session exists and assing it to a variable
if (!isset($_SESSION)) {
session_start();
}
// we can populate the session MM_Username because it is a unique identifier
if (isset($_SESSION['MM_Username'])) {
$username $_SESSION['MM_Username'];

Attached is my php file

Thanks
Attached Files
File Type: php your_account.php (32.2 KB, 3 views)
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote

  #2  
Old Dec 8th, 2007, 16:51
Rakuli's Avatar
SuperMember

SuperMember
Join Date: Sep 2007
Location: Australia
Age: 24
Posts: 956
Blog Entries: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Session data problem

Hi longstand,

The length of a session is variable based on many things. The php.ini file can determine how long the session lasts for. The defaults is that the session cookie will remain valid until the user closes their browser. Not when a user leaves your site. This allows them to go backwards and forwards during an internet "session" without having to log in again.

If you want to boot the user after they leave your site you would have to put a time limit in your php code. Say, if the user hasn't been active for 10 minutes, then they are booted and not considered logged in anymore.

PHP: Select all



// when user logs in, set the sessions variables

$_SESSION['MM_Username'] = 'Lucianovic';
$_SESSION['last_action'] = time(); 
Okay now that you have store the time they logged-in into the session, you can run a check for each page they visit..

PHP: Select all



// Is there a session
if (!isset($_SESSION))
       
session_start();

$activeThreshold 600// 10 minutes, 60 * 10

// if they have set a username? AND how long ago did they log in, more than the above set time and bam! you're gone buddy

if (isset($_SESSION['MM_Username']) && time() - $_SESSION['last_active'] < $activeThreshold)
{
       
$username $_SESSION['MM_Username']
       
$_SESSION['last_active'] = time(); // reset the last active time
} else { // if they haven't moved for more than 10 minutes, destroy this session
   
session_destroy();

Cheers,
Last Blog Entry: The wannabe juggler's quest (Oct 27th, 2007)
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote
  #3  
Old Dec 8th, 2007, 16:55
Reputable Member
Join Date: Oct 2007
Location: Liverpool UK
Age: 29
Posts: 217
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Session data problem

Hello Rakuli!!!

Thanks for this, will give it a try,

Take care mate,

Oh yer look cool in yer christmas hat
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote
  #4  
Old Dec 8th, 2007, 17:48
Reputable Member
Join Date: Oct 2007
Location: Liverpool UK
Age: 29
Posts: 217
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Session data problem

Hello again mate!

That code you passed me didnt work, i got the folowing errors:

Parse error: syntax error, unexpected T_VARIABLE in C:\xampp\htdocs\Only4Stars\your_account.php on line 111

The error appears to be on this line:

$_SESSION['last_active'] = time(); // reset the last active time


Any suggestions

Cheers!
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote
  #5  
Old Dec 9th, 2007, 04:29
Rakuli's Avatar
SuperMember

SuperMember
Join Date: Sep 2007
Location: Australia
Age: 24
Posts: 956
Blog Entries: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Session data problem

The line before that is missing a semi colon
Last Blog Entry: The wannabe juggler's quest (Oct 27th, 2007)
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote
  #6  
Old Dec 9th, 2007, 12:41
Reputable Member
Join Date: Oct 2007
Location: Liverpool UK
Age: 29
Posts: 217
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Session data problem

Thanks mate!!!

It appears that its not the session data thats causing the problem, i used record sets & dragged & dropped the bindings were i wanted the profile data to display on the form & it works but only by displaying the first registered users data, any other users who logs in seems to see only the the profile from the first line of my database...

Am unsure whats causing the problems really,

Is it becuase i dragged and dropped bindings??

Maybe my profile page needs to be hand coded without using dreamweavers in built functionality??

Or is using the bindings in the way mentioned above ok, and it really is the session data??

I just dont know??

Any ideas or advise would be cool

cheers..
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote
  #7  
Old Dec 9th, 2007, 14:46
Reputable Member
Join Date: Oct 2007
Location: Liverpool UK
Age: 29
Posts: 217
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Session data problem

Hello everyone, i havent had much look with solving my problem, so instead of attaching a php file with a huge amount of code, i have through together some forms to help me explain my problem better:

First i created a signup registration form, and it works just fine, see code below:

PHP: Select all

<?php require_once('Connections/dbfinal.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  
$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;
}
}
$editFormAction $_SERVER['PHP_SELF'];
if (isset(
$_SERVER['QUERY_STRING'])) {
  
$editFormAction .= "?" htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  
$insertSQL sprintf("INSERT INTO tbl_user (username, useraddress, userlogin, userpassword, userarea) VALUES (%s, %s, %s, %s, %s)",
                       
GetSQLValueString($_POST['username'], "text"),
                       
GetSQLValueString($_POST['useraddress'], "text"),
                       
GetSQLValueString($_POST['userlogin'], "text"),
                       
GetSQLValueString($_POST['userpassword'], "text"),
                       
GetSQLValueString($_POST['userarea'], "text"));
  
mysql_select_db($database_dbfinal$dbfinal);
  
$Result1 mysql_query($insertSQL$dbfinal) or die(mysql_error());
  
$insertGoTo "Signup_succesfull.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  
header(sprintf("Location: %s"$insertGoTo));
}
mysql_select_db($database_dbfinal$dbfinal);
$query_rsUser "SELECT * FROM tbl_user";
$rsUser mysql_query($query_rsUser$dbfinal) or die(mysql_error());
$row_rsUser mysql_fetch_assoc($rsUser);
$totalRows_rsUser mysql_num_rows($rsUser);
mysql_select_db($database_dbfinal$dbfinal);
$query_rsArea "SELECT areaname FROM tbl_area";
$rsArea mysql_query($query_rsArea$dbfinal) or die(mysql_error());
$row_rsArea mysql_fetch_assoc($rsArea);
$totalRows_rsArea mysql_num_rows($rsArea);
?><!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>Register</title>
<style type="text/css">
<!--
.style1 {
 font-family: Verdana, Arial, Helvetica, sans-serif;
 font-size: 12px;
}
-->
</style>
</head>
<body>
<form action="<?php echo $editFormAction?>" method="post" name="form1" id="form1">
  <table align="center">
    <tr valign="baseline">
      <td nowrap="nowrap" align="right"><span class="style1">Your Name:</span></td>
      <td><input type="text" name="username" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right" nowrap="nowrap" class="style1">Address:</td>
      <td><input type="text" name="useraddress" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right" nowrap="nowrap" class="style1">Userlogin:</td>
      <td><input type="text" name="userlogin" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right" nowrap="nowrap" class="style1">Userpassword:</td>
      <td><input type="text" name="userpassword" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right" nowrap="nowrap" class="style1">Your City:</td>
      <td><select name="userarea">
        <?php 
do {  
?>
        <option value="<?php echo $row_rsArea['areaname']?>" ><?php echo $row_rsArea['areaname']?></option>
        <?php
} while ($row_rsArea mysql_fetch_assoc($rsArea));
?>
      </select>
      </td>
    </tr>
    <tr> </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">&nbsp;</td>
      <td><input type="submit" value="Insert record" /></td>
    </tr>
  </table>
  <input type="hidden" name="MM_insert" value="form1" />
</form>
<p>&nbsp;</p>
</body>
</html>
<?php
mysql_free_result
($rsUser);
mysql_free_result($rsArea);
?>
I then created a login form, and it works just fine, see code below:

PHP: Select all

<?php require_once('Connections/dbfinal.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  
$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['PHP_SELF'];
if (isset(
$_GET['accesscheck'])) {
  
$_SESSION['PrevUrl'] = $_GET['accesscheck'];
}
if (isset(
$_POST['login_name'])) {
  
$loginUsername=$_POST['login_name'];
  
$password=$_POST['password'];
  
$MM_fldUserAuthorization "";
  
$MM_redirectLoginSuccess "Your_account.php";
  
$MM_redirectLoginFailed "Login.php";
  
$MM_redirecttoReferrer true;
  
mysql_select_db($database_dbfinal$dbfinal);
  
  
$LoginRS__query=sprintf("SELECT userlogin, userpassword FROM tbl_user WHERE userlogin=%s AND userpassword=%s",
    
GetSQLValueString($loginUsername"text"), GetSQLValueString($password"text")); 
   
  
$LoginRS mysql_query($LoginRS__query$dbfinal) or die(mysql_error());
  
$loginFoundUser mysql_num_rows($LoginRS);
  if (
$loginFoundUser) {
     
$loginStrGroup "";
    
    
//declare two session variables and assign them
    
$_SESSION['MM_Username'] = $loginUsername;
    
$_SESSION['MM_UserGroup'] = $loginStrGroup;       
    if (isset(
$_SESSION['PrevUrl']) && true) {
      
$MM_redirectLoginSuccess $_SESSION['PrevUrl']; 
    }
    
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 id="form1" name="form1" method="POST" action="<?php echo $loginFormAction?>">
  <table width="416" height="117" border="0" cellpadding="0" cellspacing="0">
    <tr>
      <td width="163"><div align="right"><strong>Login name:</strong></div></td>
      <td width="253"><input type="text" name="login_name" id="login_name" /></td>
    </tr>
    <tr>
      <td><div align="right"><strong>Password:</strong></div></td>
      <td><input type="text" name="password" id="password" /></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><input type="submit" name="button" id="button" value="Submit" /></td>
    </tr>
  </table>
</form>
</body>
</html>
Once the user has logged in succesfully they are sent to the your account.php page were i need there data from the database to load once they have logged in successfully, see code below:

PHP: Select all

<?php
 
// check if session exists and assing it to a variable
if (!isset($_SESSION)) {
 
session_start();
}
// we can populate the session MM_Username because it is a unique identifier
if (isset($_SESSION['MM_Username'])) {
 
$username $_SESSION['MM_Username'];
}
 
?>
 
 
<!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>Your Account</title>
<style type="text/css">
<!--
.style1 {
 font-family: Verdana, Arial, Helvetica, sans-serif;
 font-size: 12px;
}
-->
</style>
</head>
<body>
<table width="315" height="172" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="157"><span class="style1">Your Name:</span></td>
    <td width="158">&nbsp;</td>
  </tr>
  <tr>
    <td class="style1">Address:</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td class="style1">Your City:</td>
    <td>&nbsp;</td>
  </tr>
</table>
</body>
</html>
The above is the part i am having trouble with, i need the data from the logged in user to display in the your_account.php page each time they log in. Now i no its a lot of code but it all works fine, apart from the data loading into the your_account.php page once user has logged in.

Below is my working database file called dbfinal

-- MySQL Administrator dump 1.4
--
-- ------------------------------------------------------
-- Server version 5.0.45-community-nt

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

--
-- Create schema dbfinal
--
CREATE DATABASE IF NOT EXISTS dbfinal;
USE dbfinal;
--
-- Definition of table `tbl_area`
--
DROP TABLE IF EXISTS `tbl_area`;
CREATE TABLE `tbl_area` (
`areaid` int(10) unsigned NOT NULL auto_increment,
`areaname` varchar(45) collate latin1_general_ci NOT NULL,
PRIMARY KEY (`areaid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
--
-- Dumping data for table `tbl_area`
--
/*!40000 ALTER TABLE `tbl_area` DISABLE KEYS */;
/*!40000 ALTER TABLE `tbl_area` ENABLE KEYS */;

--
-- Definition of table `tbl_user`
--
DROP TABLE IF EXISTS `tbl_user`;
CREATE TABLE `tbl_user` (
`userid` int(10) unsigned NOT NULL auto_increment,
`username` varchar(45) collate latin1_general_ci NOT NULL,
`useraddress` varchar(45) collate latin1_general_ci NOT NULL,
`userlogin` varchar(45) collate latin1_general_ci NOT NULL,
`userpassword` varchar(45) collate latin1_general_ci NOT NULL,
`userarea` varchar(45) collate latin1_general_ci NOT NULL,
PRIMARY KEY USING BTREE (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
--
-- Dumping data for table `tbl_user`
--
/*!40000 ALTER TABLE `tbl_user` DISABLE KEYS */;
/*!40000 ALTER TABLE `tbl_user` ENABLE KEYS */;



/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote
  #8  
Old Dec 9th, 2007, 15:04
alexgeek's Avatar
Moderator

SuperMember
Join Date: Jul 2007
Location: Webforumz 24/7
Age: 15
Posts: 3,812
Blog Entries: 9
Thanks: 2
Thanked 2 Times in 2 Posts
Re: Session data problem

What data do you need to display?
And the data is from the tbl_user table right?
Last Blog Entry: 3D Chess in your browser! (Mar 14th, 2008)
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote
  #9  
Old Dec 9th, 2007, 15:13
Reputable Member
Join Date: Oct 2007
Location: Liverpool UK
Age: 29
Posts: 217
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Session data problem

The data is from the tbl_user table & i need the data from the coloumns: username, useraddress, & usercity to display in the your_account.php page once the user has logged in.

The login system works & links the user who has succesfully logged in to the your_account.php page. In the your_account.php page you will notice there is a table, the table is were i wnat the logged in users data to display..

So say like joe bloggs logs in i would like his data from the database to automatically show in the your_account.php page & dissapear once they leave the site..

Cheers Alex
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote
  #10  
Old Dec 9th, 2007, 16:15
alexgeek's Avatar
Moderator

SuperMember
Join Date: Jul 2007
Location: Webforumz 24/7
Age: 15
Posts: 3,812
Blog Entries: 9
Thanks: 2
Thanked 2 Times in 2 Posts