Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

php session problem

Options
  • 26-09-2006 2:56pm
    #1
    Registered Users Posts: 673 ✭✭✭


    Hey,

    Im having problems with my session variables.

    When a user logs into my site their session variables such as username, email address, etc are stored e.g. their name is stored as
    $_SESSION['full_name'] = $row['full_name'];
    

    I then use the $_SESSION to display their name once logged in.

    If i then need to call info from the website users table again e.g.
    $query = "SELECT *
    		FROM website_users
    		ORDER BY full_name
    		";
    
    		$results = mysql_query($query)
    			or die(died);
    
    		while ($rows = mysql_fetch_array($results)) {
    		extract ($rows);
    

    for something else this seems to reset all my session variables to to the last record it found from my SELECT query.

    The displayed user name now appears as the username from the last record found in my SELECT query. It is also resetting every other session variable.

    Anyone know where im going wrong?

    Thanks


Comments

  • Closed Accounts Posts: 70 ✭✭vito


    first you are selecting the entire table in your query - better to only select the record you need for that particular user:

    <code>$query = "SELECT *
    FROM website_users
    WHERE full_name = $full_name
    ORDER BY full_name
    ";
    </code>

    As far as I can see the reason the session is set to the last username is because you have a while statement so it is parsing through the results until it gets to the last row.


  • Registered Users Posts: 673 ✭✭✭Bananna man


    vito wrote:
    first you are selecting the entire table in your query - better to only select the record you need for that particular user:

    <code>$query = "SELECT *
    FROM website_users
    WHERE full_name = $full_name
    ORDER BY full_name
    ";
    </code>

    As far as I can see the reason the session is set to the last username is because you have a while statement so it is parsing through the results until it gets to the last row.

    Would i not need to set the new variables from the query to session variables though for them to change the session variable values?

    For example, my session is set, i then run this new query where the 'full_name' variable is processed. When i call the session again it is now set to the 'full_name' variable taken from the last database query even though i didnt satate
    $_SESSION['full_name'] = $row['full_name'];
    
    .


  • Closed Accounts Posts: 1,200 ✭✭✭louie


    every user that is in the database has an id.
    store that into a session when they login.
    If you need to make a call to the database to retrieve their details you use that session to do so. Their name might have duplicates, where the id is unique.
    $sSql = "select * from `your_table` where `user_id`='".$_SESSION['sessionid']."' order by `full_name` limit 0,1";
    

    Also make sure that the $_SESSION has some sort of value and is numeric as well to prevent dodgy sql statements.

    If you already have the $_SESSION set you don't need that call to the database at all.


  • Closed Accounts Posts: 70 ✭✭vito


    Would i not need to set the new variables from the query to session variables though for them to change the session variable values?

    Yes
    For example, my session is set, i then run this new query where the 'full_name' variable is processed. When i call the session again it is now set to the 'full_name' variable taken from the last database query even though i didnt satate
    $_SESSION['full_name'] = $row['full_name'];
    
    .

    Sorry this is not possible. I'm sure this may be happening but something somewhere has to set that variable. At a guess I would say you might find a single = where you meant to have ==? What happens if you have no matching result from database? Are you 100% sure that the correct variable is being copied to $_SESSION?

    Somewhere in your code the variable in being set to the last 'full_name' from the table. Without the full code to debug it's hard to give any further suggestions. Sorry :(


  • Registered Users Posts: 673 ✭✭✭Bananna man


    This aint the first time this has happened to me so there's something basic im doing wrong. :mad:

    Here is the code that is used when someone logs into the site. The session variables are set here also.
    <?php
    require_once 'conn.php';
    
    if (isset($_POST['action'])) {
     switch ($_POST['action']) {
      case 'Login':
       
        $sql = "SELECT user_id, access_lvl, full_name, company_name, address, telephone, email, password, reference_number
            FROM my_table
            WHERE email='" . $_POST['email'] . "'
            AND password ='" . $_POST['password'] . "'
    		";
        $result = mysql_query($sql)
         or die('Could not look up user information; ' . mysql_error());
    
        if ($row = mysql_fetch_array($result)) {
         session_start();
         $_SESSION['user_id'] == $row['user_id'];
         $_SESSION['access_lvl'] == $row['access_lvl'];
         $_SESSION['full_name'] == $row['full_name'];
         $_SESSION['company_name'] == $row['company_name'];
         $_SESSION['address'] == $row['address'];
         $_SESSION['telephone'] == $row['telephone'];
         $_SESSION['email'] == $row['email'];
         $_SESSION['password'] == $row['password'];
         $_SESSION['reference_number'] == $row['reference_number'];
        }
    	
    	if (isset($_SESSION['email'])
         and isset($_SESSION['password']))
       {
    	header("Location:http://www.xxxxx.order_online.php"); 
    	}
    	
    	else {
    	header("Location: ../xxxxxx/invalid_login_details.php"); 
    	}
    	break;
    
    	case 'Logout':
       	session_start();
       	session_unset();
       	session_destroy();
    	
    	header("Location: http://www.xxxxxxx/order_online.php"); 
    
       	break;
    
     }
    }
    ?>
    

    If someone logs in with this code, when they are redirected back to the main page in the right hand corner i have a thing that say's you are currently logged in as ............ I use the $_SESSION here.

    Then if they go to this page, the following script runs which shows the records held in the database for the user who has the specific reference number that was posted in 'textfield2'.
    <?php 
    
    						
    		$search_account_number = $_POST['textfield2'];
    		
    		echo "<table width='1120' border='1' cellpadding='0' cellspacing='0' background='../Website%20Images/14.jpg' class='style6'>
          <tr>
            <td width='70' height='20' class='style6'>User ID</td>
            <td width='140'>Full Name </td>
            <td width='180'>Company Name </td>
            <td width='200'>Address</td>
            <td width='100'>Telephone</td>
            <td width='180'>Email</td>
            <td width='100'>Password</td>
            <td>Account Number </td>
          </tr>
        </table>";
    						
    		$query = "SELECT  *
    		FROM my_table
    		WHERE reference_number = '".$search_account_number."'
    		";
    
    		$results = mysql_query($query)
    			or die(mysql_error());
    			
    
    		if ($rows = mysql_fetch_array($results)) {
    		extract ($rows);
    
    		
    		echo "<table width='1120' border='1' cellspacing='0' cellpadding='0' class='main_text'>
          <tr>
            <td width='70'>".$user_id."</td>
            <td width='140'>".$full_name."</td>
            <td width='180'>".$company_name."</td>
            <td width='200'>".$address."</td>
            <td width='100'>".$telephone."</td>
            <td width='180'>".$email."</td>
            <td width='100'>".$password."</td>
            <td>".$reference_number."</td>
          </tr>
        </table>";
    	}
    		else {
    		echo "<br><br><span class='headings'>No customer details found for the account number entered.</span>
    		";
    		}
    
    		
    		
    		?>
    

    After this, if i go back to the main page the welcome note in the right hand corner will now display the last 'full_name' variable from the query above even though this code has nothing about resetting session variables. All my session variables have changed, not just the 'full_name' variable.

    Can anyone see where im going wrong with this?

    This is driving me insane!!!!


  • Advertisement
  • Closed Accounts Posts: 1,200 ✭✭✭louie


    I can not see why that would happen. A session should stay until explicitly destroyed.

    Make sure in one of your forms you don't have the login page included and a hidden field named 'action' because if you do then the login code runs again and if not found in the database cleans up the sessions.


  • Registered Users Posts: 683 ✭✭✭Gosh


    There's 2 problems with your code

    $_SESSION == $row;

    should be

    $_SESSION = $row;

    i.e. 1 = sign , not 2

    The second is to do with the extract($rows) command - if there are existing variables with the same name (i.e. your session variables) they are being overwritten.

    Try running the following code and you'll see what I mean
    <?php
    
    session_start();
    $_SESSION['user_id'] = "xxxx";
    $_SESSION['access_lvl'] = 1;
    $_SESSION['full_name'] = "yyyyy";
    
    $var_array = array("user_id" => "aaaaaa",
                       "full_name" => "ccccccc");
                       
    extract ($var_array);
    
    echo $_SESSION['user_id'] . " " . $_SESSION['access_lvl'] . " " . $_SESSION['full_name'];
    ?>
    
    If you run this code, it displays

    aaaaaa 1 ccccccc

    not

    xxxx 1 yyyyy

    as $_SESSION and $_SESSION are being overwritten by the extract ($var_array) command


  • Closed Accounts Posts: 1,200 ✭✭✭louie


    Jesus i haven't noticed the double == there.
    My apologies for that.

    double == is used for the if(foo=="foo") not for setting a variable, session or array.


  • Registered Users Posts: 673 ✭✭✭Bananna man


    Cheers,

    I actually had the session variables with inly one = sign but just tried it with the == a while ago.

    I changed the session name's to:
    $_SESSION == $row;

    so the session variable is now session_user_id and when i want it seperatly from the database it will be just user_id. It seems to be working fine now though. How should i do my code differently in future to avoid this problem? Should i just make sure to always name the sessiion variables differently from any variables stored in my database?


  • Registered Users Posts: 683 ✭✭✭Gosh


    Be aware of exactly what the PHP extract command does - see http://ie2.php.net/extract

    especially the second and third parts of the command


  • Advertisement
  • Closed Accounts Posts: 1,200 ✭✭✭louie


    That will be a good practice.
    Myself I add x_ before the name so if I have full_name in the database i'll set the session as $s_full_name and variables as $x_full_name. If I need another variable again i'll choose $y_full_name


  • Registered Users Posts: 683 ✭✭✭Gosh


    You can achieve that with the extract command using the second parameter as EXTR_PREFIX_ALL and specify the third parameter as a prefix for variables extracted, for example

    [PHP]
    extract ($rows, EXTR_PREFIX_ALL, "temp")
    [/PHP]

    will extract the variables prefixed with $temp_


  • Closed Accounts Posts: 70 ✭✭vito


    Gosh wrote:
    You can achieve that with the extract command using the second parameter as EXTR_PREFIX_ALL and specify the third parameter as a prefix for variables extracted, for example

    [PHP]
    extract ($rows, EXTR_PREFIX_ALL, "temp")
    [/PHP]

    will extract the variables prefixed with $temp_

    I'm curious - I always use a DB abstract layer so I've never used extract.

    How can extract($database_row) result in $_SESSION? :confused:

    Wouldn't that simply overwrite any pre-existing variable $main_name?

    How exactly were those array values being written to the $_SESSION array via the extract()?


  • Registered Users Posts: 683 ✭✭✭Gosh


    Vito - I, myself, have never used the extract command - if you read the PHP manual description here it should be clear. Particularly the use of the second parameter which is do with variable name collision.

    In the original example I gave where the $_SESSION variables were being overwritten this is because the second parameter was defaulting to EXTR_OVERWRITE ( If there is a collision, overwrite the existing variable.) - however if you have more than 1 associative array with the same key values it doesn't do this - see the example below

    [php]
    session_start();
    $_SESSION = "xxxx";
    $_SESSION = 1;
    $_SESSION = "yyyyy";

    $another_array = array("user_id" => "mmmmmm",
    "full_name" => "nnnnnn");

    $var_array = array("user_id" => "aaaaaa",
    "full_name" => "ccccccc");

    extract ($var_array);

    echo $_SESSION . " " . $_SESSION . " " . $_SESSION;
    [/php]

    In this case, at the time of the extract there are 2 associative arrays with the same key values so PHP wouldn't know which one to overwrite.


Advertisement