drlh197610 2013-08-26 01:10
浏览 45

MySQL插入/更新问题

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?

  • 写回答

1条回答 默认 最新

  • douzheyo2617 2013-08-26 01:34
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况