Return primary key after insertion into Mysql

Asked

Viewed 480 times

0

I need to insert into my database two tables, one of the tables has a primary key and the other will use this value as a foreign key.

My question is: How can I return the value of this primary key right at the time of insertion? Or how I can do the PK search, without the risk of me taking the value of another tuple that was inserted at the same time or soon after?

Thank you

  • on Trigger or programming?

2 answers

0


When it comes to Mysqli you can use the function insert_id().

Example of documentation:

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* drop table */
$mysqli->query("DROP TABLE myCity");

/* close connection */
$mysqli->close();
?>

0

Otherwise if it is mysqli, if you are not using a class (object oriented), the function insert_id(); can be used as follows:

mysqli_insert_id($conexao_com_mysql) 

instead of:

$mysqli->insert_id

This function returns the last primary key inserted in that session, with no chance of you taking another primary key other than the one you just entered.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.