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条)

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题