What are the advantages of using mysql_insert_id over complex queries to retrieve the last inserted ID?

When inserting data into a MySQL database, it is important to retrieve the last inserted ID for various reasons, such as linking the new data to other tables or for logging purposes. Instead of using complex queries to retrieve the last inserted ID, it is more efficient and straightforward to use the built-in function mysql_insert_id(). This function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute.

// Insert data into the database
$query = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
$result = mysqli_query($connection, $query);

// Get the last inserted ID
$last_inserted_id = mysqli_insert_id($connection);

echo "Last Inserted ID: " . $last_inserted_id;