// connect to MySQL database $conn = mysqli_connect("localhost", "username", "password", "dbname"); // insert data into table mysqli_query($conn, "INSERT INTO users (name, email) VALUES ('John Doe', 'johndoe@email.com')"); // retrieve the inserted ID $id = mysqli_insert_id($conn); echo "New record created with ID: " . $id;
// connect to PostgreSQL database $conn = pg_connect("host=localhost port=5432 dbname=mydatabase user=username password=mypassword"); // insert data into table pg_query($conn, "INSERT INTO customers (name, email) VALUES ('Emma Smith', 'emma@email.com')"); // retrieve the inserted ID $id = pg_last_oid($conn); echo "New record created with ID: " . $id;This code connects to a PostgreSQL database and inserts a new customer into the "customers" table. After the insert, the pg_last_oid function is used to get the ID generated by the auto-increment column. Finally, the ID is printed to the screen. Package/Library: PostgreSQL extension In conclusion, the database insert_id function is a useful feature in PHP that allows developers to retrieve the ID generated by an auto-increment column after inserting data into a database table. The specific function used depends on the database management system being used and the preferred PHP extension. For MySQL, developers can use the mysqli_insert_id function from the MySQLi extension, while the pg_last_oid function from the PostgreSQL extension can be used for PostgreSQL databases.