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 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 这个公式写进SIMULINK中的function模块的代码中应该是什么样的
  • ¥15 javaweb登陆的网页为什么不能正确连接查询数据库
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题