I have two tables created with this:
CREATE TABLE t1 (id NUMBER GENERATED AS IDENTITY);
CREATE TABLE t2 (id NUMBER GENERATED AS IDENTITY);
Im inserting some data into t1 and then i need to insert the ID generated in that insert into t2.
For example:
"insert into t1 (name, description) values ('asd','dsa')"
**getting that autogenerated ID
"insert into t2 (idFromt1,name) values (idFromt1,'sarasa')"
I saw many examples doing:
"insert into t1 (name, description) values ('asd','dsa') returning ID into inserted_id";
But i cant/dont know how to retrieve that "inserted_id" variable from php to make the second insert.
Either use PDO::lastInsertId
or
SELECT MAX(id) FROM table;
Example:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
Don't use
SELECT MAX(id) FROM table;
Because it's not safe if some other insert query will be executed before select and it will not work for you in a transaction.
You can (should?) use the returning
value.
For example, with PDO :
$query = "insert into t1 (name, description) values ('asd','dsa') returning ID";
$stmt = $pdo->query($query);
$id = $stmt->fetchColumn();
I was googling about PDO and come into this:
$qry="INSERT INTO t1 (NOMBRE) VALUES ('sarasa') returning ID into :inserted_id";
$parsed = oci_parse($this->conn, $qry);
oci_bind_by_name($parsed, ":inserted_id", $idNumber,32);
oci_execute($parsed);
echo $idNumber;
so i asumed oci_bind_by_name was one direction only, but no. That saves into the variable $idNumber the generated id and was exactly what i needed. Thanks all for your answers.