Return primary key after insertion in MySQL

0

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

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

Thank you

    
asked by anonymous 28.04.2017 / 05:29

2 answers

0

If it's MySQLi you can use the function insert_id() .

Sample 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();
?>
    
28.04.2017 / 06:05
0

Another way when dealing with mysqli, if you do not use 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 entered in that session, without the chance of you getting another primary key other than the one you just entered.

    
28.04.2017 / 06:44