dsfds2353 2012-09-25 14:05
浏览 14
已采纳

从插入行查询返回列条目 - MySQL和PHP

Heres the scenario: I am supposed to make a small site where user can register, I am using a table named users with fields

userid int unsigned auto_increment,
name varchar(50),
gender enum('m','f'),
time datetime,
joiningyear int unsigned,
primary key (userid)

When I insert a new user I am also supposed to log him in by saving an encrypted form of his userid as a cookie. The problem is this, if userid is already used, it is auto incremented by 1, as is obvious. I would like to recieve this new value as an output of my insert query, without adding another query that fetches it, this will makes things easy.

Currently I am using two seperate queries one checking if randomly chosen userid is already taken and second inserting the entry. Insert into users(......) values(...)

Is there a way to achieve this with one query?

  • 写回答

2条回答 默认 最新

  • dongli7870 2012-09-25 14:09
    关注

    Depending on your MySql adapter you can use:

    mysqli_insert_id or PDO::lastInsertId. There is also mysql_insert_id but described with:

    Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.

    If you are using any framework, it should support returning last inserted id.

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?