Search code examples
databaseinsertreturnidentifierauto-increment

return id from database after insert


i have a php that responds to an ajax and inserts a row into database, this is the code

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
    }

what i want to achieve it to make this code to return the id that the database auto-incremented and echo it back to the ajax function, the problem is that i cant get the last id because someone else might insert data after me and get the wrong id.. i would be rly happy to know if there is a workaround on this issue Thanks in advance, Daniel!

EDIT: i want to add that i am using PostgreSQL as database, maybe it has a module to do that


Solution

  • Checking http://wiki.postgresql.org/wiki/FAQ#How_do_I_get_the_value_of_a_SERIAL_insert.3F, it seems you can do queries like:

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

    I'm assuming you call pg_fetch_assoc() on the query resource and treat it like a SELECT?