PHP/MySQL insert row then get 'id'

To insert a row into a MySQL database table and get the id of the inserted row in PHP, you can use the mysqli_insert_id() function. This function returns the id (also called the "primary key") of the last inserted row or sequence value.

Here is an example of how to use mysqli_insert_id() to insert a row into a MySQL table and get the id of the inserted row:

<?php

// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($mysqli->connect_errno) {
  printf("Connect failed: %s\n", $mysqli->connect_error);
  exit();
}

// Insert a row into the table
$query = "INSERT INTO table (column1, column2) VALUES ('value1', 'value2')";
$result = $mysqli->query($query);

// Get the id of the inserted row
$id = $mysqli->insert_id;

// Close connection
$mysqli->close();

?>

This example assumes that you have already connected to the MySQL database using the mysqli_connect() function, and that you have a table named "table" with columns "column1" and "column2".

Watch a course Learn object oriented PHP

Note: This example uses the MySQLi extension. If you are using the older MySQL extension, you can use the mysql_insert_id() function instead.