doune1000 2016-08-03 06:47
浏览 53
已采纳

php mysql - 将user_id添加到会话变量

When I register a user I add them to a database and they get an id which is auto generated by auto_increment. Now I'm trying to add that id to a session variable so I can use it on other pages in the website and manipulate their row in the database. This is what I have so far.

This line adds the form inputs to the db when the user registers:

$insert = mysql_query("INSERT INTO users (`email`, `password`) VALUES ('example','values'))");

Then I'm trying to get the user_id into a variable that I can use on other pages of the website. I'm trying this:

if ($insert) {
  $select_id = mysql_query("SELECT `id` from `users` WHERE `email` = '$form_input'");
  $id_arr = mysql_fetch_array($select_id);
  $id_var = $id_arr['id'];
  session_start();
  $_SESSION["Register"] = $id_var[0];
}

But it doesn't work so I'm trying a var_export to see what's in $id_var and I get a value of '3' which doesn't match the user_id that supposed to be stored in the variable.

  • 写回答

3条回答 默认 最新

  • doujiu8178 2016-08-03 06:50
    关注

    You need to iterate over the result set to get the value of id

    $id="";
    while ($row = mysql_fetch_array($select_id))   
    {    
      $id= $row ['id'];
    }
    if($id!=""){
       session_start();
       $_SESSION["Register"] = $id;
    }
    

    Note: mysql_query was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.Alternatives to this function include: mysqli_query() or PDO::query()

    Moreover, passing the values directly into the query is not safe. Please, read about SQL injection

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作