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.

    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划