How can mysqli_error() be used to troubleshoot database insertion errors in PHP?

When encountering database insertion errors in PHP, you can use the mysqli_error() function to retrieve the specific error message generated by the MySQL database. This can help you identify the cause of the issue, such as syntax errors or constraints violations, and troubleshoot it accordingly.

// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Perform database insertion
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
if (mysqli_query($connection, $sql)) {
    echo "Record inserted successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}

// Close connection
mysqli_close($connection);