【问题标题】:return id from database after insert插入后从数据库返回 id
【发布时间】:2012-03-23 12:22:49
【问题描述】:

我有一个响应 ajax 并在数据库中插入一行的 php,这是代码

if($action == "insertCalendarEvents") {
        $calendar_group = $_GET["calendar_group"];
        $event_name = "'" . $_GET["event_name"] . "'";
        $event_datestart = "'" . $_GET["event_datestart"] . "'";
        $event_datestop = "'" . $_GET["event_datestop"] . "'";
        $event_timestart = $_GET["event_timestart"] != "" ? "'" . $_GET["event_timestart"] . "'" : "null";
        $event_timestop = $_GET["event_timestop"] != "" ? "'" . $_GET["event_timestop"] . "'" : "null";
        $event_info = "'" . $_GET["event_info"] . "'";

        require_once("connect.php");
        $query = "INSERT INTO calendar_events (calendar_group, event_name, event_datestart, event_datestop, event_timestart, event_timestop, event_info) VALUES (" . $calendar_group . ", " . $event_name . ", " . $event_datestart . ", " . $event_datestop . ", " . $event_timestart . ", " . $event_timestop . ", " . $event_info . ")";
        $result = pg_query($connect, $query);
        if(!$result)
            die("error 1"); // query error
    }

我想要实现它以使此代码返回数据库自动递增的 id 并将其回显给 ajax 函数,问题是我无法获取最后一个 id,因为其他人可能会在我之后插入数据并得到错误的ID.. 我很高兴知道这个问题是否有解决方法 在此先感谢丹尼尔!

编辑:我想补充一点,我正在使用 PostgreSQL 作为数据库,也许它有一个模块可以做到这一点

【问题讨论】:

  • 似乎安全是徒劳的。

标签: database insert return identifier auto-increment


【解决方案1】:

查看http://wiki.postgresql.org/wiki/FAQ#How_do_I_get_the_value_of_a_SERIAL_insert.3F,您似乎可以进行如下查询:

INSERT INTO person (name) VALUES ('Blaise Pascal') RETURNING id

我假设您在查询资源上调用 pg_fetch_assoc() 并将其视为 SELECT?

【讨论】:

  • 非常感谢迈克尔拉什顿!这是我编程经验的一大进步,因为每次我编写与数据库相关的代码时,我都会遇到这个问题 :)
【解决方案2】:

使用 @@identity 或 scope_identity 获取您插入的最后一个索引。

在插入语句之后使用select @@identity

http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/

【讨论】:

  • 你能说得更具体些吗?我在日历事件表中有名为 event_id 的自动递增字段。我需要使用 SELECT @@event_id 吗?
  • 在这种情况下,我认为您正在寻找的是 currval()
  • 是的,我尝试过 currval 并且它工作得很好,唯一不能 100% 确定的是,如果更多的 ppl 在数据库中同时添加事件会发生什么,currval 返回的值是否比错误的值? (我的意思不是你应该得到的价值,而是别人的价值)
  • 如果你点击我发布的那个链接,你会看到他说:“不,你错了。currval() 对你当前的连接来说是“本地的”。所以在 multi 中使用它没有问题-用户环境。这就是序列的全部目的。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-06
  • 2014-12-05
  • 1970-01-01
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多