dqm83011 2016-10-06 12:03
浏览 34

插入新记录后获取UserID

I am currently working with a form where you are able to create new users. You would specify the username, firstname, etc and a new record would be inserted into the Users table in a database.

Right after the creation of an user more steps follow, but for these having the auto generated UserID in the session would be very useful.

How can I accomplish this? I tried the following:

sqlsrv_query($conn1,"INSERT INTO Users (Username, Firstname, Lastname, JobTitle)
VALUES ('$_POST[Username]', '$_POST[Firstname]', '$_POST[Lastname]', '$_POST[JobTitle]'); SELECT SCOPE_IDENTITY() AS UserID;");

$result = sqlsrv_query($conn1); $next_result = sqlsrv_next_result($result); $row = sqlsrv_fetch_array($result);
$_SESSION['UserID'] = $result;
  • 写回答

1条回答 默认 最新

  • dtevhgk028372 2016-10-06 12:40
    关注

    Use OUTPUT INSERTED in your query.

    Change Your Code Like,

    $result =  sqlsrv_query($conn1,"INSERT INTO Users 
    (Username, Firstname, Lastname, JobTitle) OUTPUT INSERTED.UserID 
    VALUES ('$_POST[Username]', '$_POST[Firstname]', '$_POST[Lastname]', '$_POST[JobTitle]'); 
    

    and you will get last inserted id in $result

    评论

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像