Please tell me how you can get the id of the newly created record in the sql table using php. Create a record in the table, too, using php.

Reported as a duplicate by AK ♦ , aleksandr barakin , 0xdb , user300000, kot-da-vinci participants on Oct 25 '18 at 17:29 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • one
    How can I get the id of the newly created record in the sql table? The answer strongly depends on the purpose for which the value is obtained, where and how it will be used. But this, practically the most important, information - alas, is absent in the question. Moreover, it is desirable to respond more broadly - describing the whole process, and not one of his small stages. Because it can easily be that you do not need to receive it at all. - Akina

1 answer 1

For mysql . Taken from php.net

 <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Ошибка соСдинСния: ' . mysql_error()); } mysql_select_db('mydb'); mysql_query("INSERT INTO mytable (product) values ('kossu')"); printf("Π˜Π΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€ послСднСй вставлСнной записи %d\n", mysql_insert_id()); ?> 

For mysqli . Taken from php.net

 <?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° соСдинСния */ if (mysqli_connect_errno()) { printf("Π‘ΠΎΠ΅Π΄ΠΈΠ½Π΅Π½ΠΈΠ΅ Π½Π΅ установлСно: %s\n", mysqli_connect_error()); exit(); } mysqli_query($link, "CREATE TABLE myCity LIKE City"); $query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)"; mysqli_query($link, $query); printf ("ID Π½ΠΎΠ²ΠΎΠΉ записи: %d.\n", mysqli_insert_id($link)); /* Π·Π°ΠΊΡ€Ρ‹Ρ‚ΠΈΠ΅ соСдинСния */ mysqli_close($link); ?> 
  • Everything is good, only mysql has long been deprecated, you need to use mysqli - AK ♦
  • tag to the mysql question - Evgeny Nikolaev
  • 2
    @YevgenyNikolaev duck is about the DBMS, and not the access library. The text of the question clearly shows the use of mysqli - teran