9

I'm trying to pull data off my sql table with php unique to the session's ID, however I only get the position that the user is in when I echo anything out!

<?php
include 'core/init.php';
$user_info = $_SESSION['user_id'];
?>
<html>....
<h1><?php echo $user_info['firstname'];?>&nbsp<?php echo $user_info['firstname'];?> </h1>

displays as:

5 5

if I log in with the fifth position in the database!

4
  • Where do you add the data into $_SESSION. I think you are missing that part
    – Ertunç
    Oct 22, 2012 at 6:43
  • $session_user_id may be empty at line $user_data = user_data($session_user_id, 'user_id', 'username', 'first_name', 'last_name', 'email'); Oct 25, 2012 at 8:26
  • 1
    Database picture is dead link Oct 28, 2012 at 0:48
  • Yes, the database image is missing. Could you fix it?
    – tftd
    Oct 28, 2012 at 19:23

7 Answers 7

3
+100

The reason why you are getting 5 is for this code:

<?php echo $user_info['firstname'];?>

is that $_SESSION['user_id'] 's value is 5. So after the assignment $user_info's value is 5. Now because the $_SESSION['user_id'] is not set to an array as your intention seems to be. The result is that $user_info is taken as a string and ['firstname'] evaluates to [0]. If you like, you can update the ID 5 to 54, etc. You will always get the first character of your ID.

To correct this, try changing the last 2 lines before the return in your user_data function to:

$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE `user_id` = $user_id"));
$data = array_merge(array($user_id), $data);
return $data;

if (logged_in() === true) { 
    $user_data = user_data($_SESSION['user_id'], 'username', 'first_name', 'last_name',     'email');
    $user_data = user_data($session_user_id, 'user_id', 'username', 'first_name', 'last_name', 'email');
}

to:

if (logged_in() === true) { 
    $user_data = user_data($_SESSION['user_id'], 'username', 'first_name', 'last_name', 'email');
    $_SESSION['user_id'] = $user_data;
}
2
if (logged_in === true) { 

should be

if (logged_in()) { 
1
  • I've changed it however the user's data still doesn't echo out! Oct 18, 2012 at 19:26
0

for me it seems like you forgot to update data in session. lets say here:

if (logged_in() === true) { 
    $user_data = user_data($_SESSION['user_id'], 'username', 'first_name', 'last_name', 'email');
    $user_data = user_data($session_user_id, 'user_id', 'username', 'first_name', 'last_name', 'email');

    $_SESSION = array_merge($_SESSION, $user_data);
}

hope it helps you to resolve your problems.

2
  • got this errror "Warning: array_merge() [function.array-merge]: Argument #2 is not an array in /home/emusauce/public_html/classm8.net/test/core/init.php on line 12 " Oct 22, 2012 at 6:05
  • ok. could you please show what is the result of user_data function?
    – chmeliuk
    Oct 22, 2012 at 6:18
0

What I see that your in this line

<h1><?php echo $user_info['firstname'];?>&nbsp<?php echo $user_info['firstname'];?> </h1>

you are using "firstname", whereas in database it is named as "first_name", see underscore

<h1><?php echo $user_info['first_name'];?>&nbsp<?php echo $user_info['first_name'];?> </h1>

Let me know if this solves or not as I too want to know its answer

3
  • The problem seems different cause he gets output 5 even when he uses as $user_info['firstname']. I think this indicates he is populating session values incorrectly.
    – Ertunç
    Oct 22, 2012 at 6:56
  • yes, seems so, I would request you to please give your code and db, if possible so I can trace the exact problem
    – Ravi Kumar
    Oct 22, 2012 at 7:16
  • send it via mail on [email protected]
    – Ravi Kumar
    Oct 22, 2012 at 10:15
0

May help you some changes in your code

function user_data($user_id) {
    $data = array ();
    $user_id = (int)$user_id;

    $func_num_args = func_num_args();
    $func_get_args = func_get_args();

    if ($func_num_args > 1) {
        unset($func_get_args[0]);

        $fields = '`'. implode('`, `', $func_get_args). '`';
        echo '<br>'.
        $que =  "SELECT $fields FROM `users` WHERE `id` = $user_id";
        $data = mysql_fetch_assoc(mysql_query($que));
        print_r ($data);
        return $data;
        }
}

function logged_in() {
    return (isset($_SESSION['id'])) ? true : false;
}

if (logged_in() === true) { 
    $user_data = user_data($_SESSION['user_id'], 'username', 'firstname', 'email');
    //$user_data = user_data($session_user_id, 'user_id', 'username', 'firstname', 'email');
    print_r($user_data);
}
echo 
$user_info = $user_data;//$_SESSION['user_id'];
?>
<h1><?php echo $user_info['firstname'];?>&nbsp<?php echo $user_info['firstname'];?> </h1>
0
function user_data($data=array(),$whereData=array()) {
  $str='';
  if(isset($whereData) && is_array($whereData))
   {
         foreach($whereData as $key=>$val)
    {
        if($val!='')
        if($str=='')
            $str     =  $key." = '".$val."'";
        else
            $str    .=  " AND ".$key." = '".$val."'";
    }
   }
      $condition =
       $fields = implode(',' , $data);
       if($str!=''){
        $data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE  $str"));
        }
         else
          {
                $data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` ));
          }
        return $data;
        print_r ($data);
        }
}

and

 if (logged_in() === true) {
  $data = array('username', 'first_name', 'last_name', 'email');
  $where=array('user_id'=>$_SESSION['user_id']) 
  $_SESSION['data'] = user_data($data, $where);

}

and

<?php
include 'core/init.php';
$user_info = $_SESSION['data'];
?>
<html>....
<h1><?php echo $user_info['firstname'];?>&nbsp<?php echo $user_info['firstname'];?> </h1>
-1

From experience of creating large code bases in PHP and when you expand the application you will find you are using more and more data all over the place from the users table. Also, the table should only really contain the most vital data that is comonly used and you do NOT want to be sending more than 1 or 2 queries to the users table per page hit as it can soon become a bottle neck. For this reason you are better storing all of the data data (move large fields to another table or fields rarely used). Then store the whole user record in a session which means any function, class etc can use it as it becomes a superglobal and you can trust it enough to use it throughout the entire application without needed to re-query the users table again and again.

I have written a working example (suing your db table structure) and commented it all throughout explaining why i have done it the way i have and some points you might want to consider.

//change from user_data() to get_user_data() so we know we are "getting" it, makes it a little clearer
function get_user_data($user_id) {

    //protect agains sql injections
    $user_id = mysql_real_escape_string($user_id);

    //you should also be using mysqli or PDO, not the outdated mysql library - just check the php documentation if you don't believe me ;)
    $result = mysql_query("SELECT * FROM `users` WHERE `id` = '{$user_id}' LIMIT 1");

    //only if the previous query returned a result do we want to fetch an array from it
    if ($result) {
        return mysql_fetch_assoc($result);
    }

    //query didn't work (syntax error for example) so return blank array
    return array();

}

//start and restore the session
session_start();

//if first page hit, set the user details element
if (isset($_SESSION['user_details']) == false) {
    $_SESSION['user_details'] = array();
}

//if already logged in, refresh their user details incase there were any changes
if (isset($_SESSION['user_details']->user_id)) {
    //refresh the user data
    $_SESSION['user_details'] = get_user_data($_SESSION['user_details']->user_id);
}

//login
if (empty($_POST['id']) == false) {
    $_POST['id'] = trim($_POST['id']);
    if (is_numeric($_POST['id'])) {
        $_SESSION['user_details'] = get_user_data($_POST['id']);
    }
}

//logout
if (isset($_GET['logout'])) {
    if ($_GET['logout'] == session_id()) {
        $_SESSION['user_details'] = array();
    }
}

//see if logged in so we know what to display
if (empty($_SESSION['user_details'])) {
    //not logged in
    print "<form method='post' action=''><label>User ID</label><input type='text' name='id' value='5' /><input type='submit' value='Login' /></form>";
    } else {
    //is logged in
    print "<a href='?logout=" . rawurlencode(session_id()) . "'>logout</a>";
}

//proof that it works
print '<pre>';
print_r($_SESSION['user_details']);
print '</pre>';

P.S. Also you may want to start using LIMIT in your SQL queries as LIMIT 1 in the query above tells mysql that it can stop searching after it finds 1 result - and you should have an index on that column (preferably a primary index or unique index) to keep it lightening fast (or at least in the beginning anyway >< ).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.