M
M
millwright2015-12-04 02:46:48
PHP
millwright, 2015-12-04 02:46:48

How to get the ID of a newly created row in MySQL?

I create a new record in the table, which is automatically assigned an ID (auto increment), you need to immediately get this ID in order to add it to another table. I'm trying to do it like this:

try {
        $sql = "SELECT id FROM tricks WHERE trickName = :trickName";
        $s = $pdo->prepare($sql);
        $s->bindValue(':trickName', $_POST['name']);
        $s->execute();
        $result = $s->fetch();
        include 'test.php';
    } catch (Exception $ex) {
        $error = 'Error adding relations.';
        include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
        exit();
    }

The names are unique, but for some reason I get an array of two identical IDs.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nelson, 2015-12-04
@millwright

The canonical way to get the last used auto-increment id is to execute the LAST_INSERT_ID() sql query.
In addition, any database library has similar and more convenient functions.
If you are using the standard PDO extension then nl3.php.net/manual/en/pdo.lastinsertid.php

D
Dmitry Belyaev, 2015-12-04
@bingo347

MySQL is able to return lastInsertID
in PDO there is a method for this: fi2.php.net/manual/en/pdo.lastinsertid.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question