How to insert a row and then get ‘id’ with PHP/MySQL?

Spread the love

Sometimes, we want to insert a row and then get ‘id’ with PHP/MySQL.

In this article, we’ll look at how to insert a row and then get ‘id’ with PHP/MySQL.

How to insert a row and then get ‘id’ with PHP/MySQL?

To insert a row and then get ‘id’ with PHP/MySQL, we can use the mysqli_insert_id function.

For instance, we write

$link = mysqli_connect("127.0.0.1", "my_user", "my_pass", "my_db");
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);

to connect to the database with mysqli_connect.

Then we call mysqli_query function to run the insert statement.

Finally, we get the ID of the last row inserted with mysqli_insert_id.

Conclusion

To insert a row and then get ‘id’ with PHP/MySQL, we can use the mysqli_insert_id function.

Leave a Reply

Your email address will not be published. Required fields are marked *