PHP在数据库中查询Session_ID

时间:2012-02-14 15:28:26

标签: php mysql session session-variables

我一直在尝试在我的网站上找到会话ID,所以我可以用它来查询我的MySQL数据库,但我一直收到错误'未定义变量:_SESSION in ...'

这是我的代码:

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

这是我定义会话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'];

2 个答案:

答案 0 :(得分:2)

您必须在SQL查询之前启动会话: http://us.php.net/manual/en/function.session-start.php

session_start();

然后你应该得到当前的会话ID: http://us.php.net/manual/en/function.session-id.php

$current_session_id = session_id();

答案 1 :(得分:1)

在尝试写入之前你做了session_start()吗? 还试着把

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

在你尝试阅读之前,看看其中是什么。 所以你会:

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'];

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

另外,我想知道你是否可以用$ this-&gt; tablename:

来做到这一点
$qry = "Select name, email, username, _id from $this->tablename where username='$username' and password='$pwdmd5' and confirmcode='y'";

尝试:

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