Sam Jackson
Sam Jackson

Reputation: 628

PHP Querying Session_ID Inside a Database

I've been attempting to find the session id on my site so I can use it to query my MySQL database but I keep getting the error 'Undefined variable: _SESSION in...'

Here's my code:

if (mysql_num_rows(mysql_query("SELECT * FROM users WHERE _id = " . $_SESSION['_id_of_user'])))

And here is where I defined my session id:

$qry = "Select name, email, username, _id from $this->tablename where username='$username' and password='$pwdmd5' and confirmcode='y'";

$result = mysql_query($qry,$this->connection);

if(!$result || mysql_num_rows($result) <= 0)
{
    $this->HandleError("Error logging in. The username or password does not match");
    return false;
}

$row = mysql_fetch_assoc($result);

$_SESSION['name_of_user']     = $row['name'];
$_SESSION['email_of_user']    = $row['email'];
$_SESSION['username_of_user'] = $row['username'];
$_SESSION['_id_of_user']      = $row['_id'];

Upvotes: 0

Views: 1242

Answers (2)

djot
djot

Reputation: 2947

You have to start the session before your sql query: http://us.php.net/manual/en/function.session-start.php

session_start();

Then you should get the current session id with this: http://us.php.net/manual/en/function.session-id.php

$current_session_id = session_id();

Upvotes: 2

Iznogood
Iznogood

Reputation: 12853

Do you do a session_start() before trying to write to it? Also try putting

var_dump("<PRE>", $_SESSION);

before you attemptd to read from it to see whats actually in there. So you would have:

session_start();
$_SESSION['name_of_user']     = $row['name'];
$_SESSION['email_of_user']    = $row['email'];
$_SESSION['username_of_user'] = $row['username'];
$_SESSION['_id_of_user']      = $row['_id'];

and:

var_dump("<PRE>", $_SESSION);
$qry = "Select name, email, username, _id from $this->tablename where username='$username' and password='$pwdmd5' and confirmcode='y'";

Also I am wondering if you can do this with $this->tablename :

$qry = "Select name, email, username, _id from $this->tablename where username='$username' and password='$pwdmd5' and confirmcode='y'";

Try:

 $qry = "Select name, email, username, _id from ".$this->tablename." where username='$username' and password='$pwdmd5' and confirmcode='y'";

Upvotes: 1

Related Questions