So right now I'm working on a basic session system for my C# Application. I have a table with id,username, password and a session table with id, code, start.

the id columns of both tables are relative to the user logged in (id of user table is the same as session table). What I want to do is that when it sets the session it first checks to see if a session is already active, if it is then it will just update the current one, if there isn't one it will insert a new one. This works fine. My problem is that no matter what user I log in as the id is always set to 0 so I can have a max of one session active at a time.

Here is what I am currently doing:

//get id of inputted user.
$id = getUserId($username);

//first check if a session already exists that is connected to this username
$query = mysql_query("SELECT * FROM sessions WHERE(`id`='$id')") or die("Couldn't query database: <br> <br> " . mysql_error());;

if(mysql_num_rows($query) > 0) {
    //session already exists, update it.
    mysql_query("UPDATE sessions SET `code`='$code', `start`='$date' WHERE(`id`='$id')") or die("Failed to update session: <br> <br> " . mysql_error());
} else {
    //session doesn't exist so lets create one
    mysql_query("INSERT INTO sessions (`id`,`code`,`start`) VALUES('$id','$code', '$date')") or die("Failed to create session: <br> <br> " . mysql_error());

Also my getUserId function:

function getUserId($username) {
    $query = mysql_query("SELECT * FROM users WHERE(`username`='$username')");
    $row = mysql_fetch_row($query);
    return $row[0];

My question, if you didn't get it already. Is why is it that the 'id' is always being set to 0 even though the getUserId() function is returning the proper id of the user?

Any suggestions?

dphe5602 如果你切换你的函数返回一个assoc_array并使用$row['id']会发生什么?或者只选择id,而不是*..?
接近 7 年之前 回复
dongzhan9100 是的,我知道我不应该。但出于这个目的,我并不担心在这一点上转换。
接近 7 年之前 回复
douhuitan5863 建议,不要在新代码中使用mysql_*函数。它们不再维护,并且已被正式弃用。看到红色的盒子?了解准备好的语句,并使用PDO或MySQLi-本文将帮助您确定哪些。如果您选择PDO,这是一个很好的教程。
接近 7 年之前 回复


刚刚发现了我的错误。 </ p>

我有这行调用setSession函数。</ p>

  // set session 
setSession($ username。$ password); \ n </ code> </ pre>

它应该只是解析用户名,但我忘记了取出$ password。 因此,当它正在查找用户名'user1'时,它实际上将查找'user1password',因此返回0,因为这些细节中没有记录。</ p>
</ div>



Just found the mistake on my part.

I have this line which call the setSession function.

//set session
setSession($username. $password);

It is supposed to be only parsing the username, but I forgot tot take $password out. So when it is looking for the username 'user1' for example it will actually be looking for 'user1password' and therefore returning the 0 due to no records existing with those details.

Csdn user default icon