Answer the question
In order to leave comments, you need to log in
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();
}
Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question