How can proper error handling be implemented when inserting data into a database using PHP?

When inserting data into a database using PHP, proper error handling can be implemented by using try-catch blocks to catch any potential exceptions that may occur during the database operation. This allows for more graceful handling of errors and prevents the script from crashing unexpectedly.

try {
    // Connect to the database
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    
    // Prepare the SQL statement
    $stmt = $pdo->prepare("INSERT INTO mytable (column1, column2) VALUES (:value1, :value2)");
    
    // Bind parameters
    $stmt->bindParam(':value1', $value1);
    $stmt->bindParam(':value2', $value2);
    
    // Execute the statement
    $stmt->execute();
    
    echo "Data inserted successfully!";
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}