How can PHP be used to display database error messages when performing operations like inserting data into a MySQL or MariaDB table?

When performing operations like inserting data into a MySQL or MariaDB table using PHP, it is important to handle database errors properly to provide meaningful feedback to users. One way to display database error messages is by using the mysqli_error() function in PHP. This function retrieves the error message from the most recently executed MySQL function.

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

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Perform insert operation
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
if ($mysqli->query($sql) === TRUE) {
    echo "Record inserted successfully";
} else {
    echo "Error: " . $mysqli->error;
}

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