How can error reporting be improved in PHP scripts to catch potential issues like failing to insert data into a database?

To improve error reporting in PHP scripts and catch potential issues like failing to insert data into a database, you can use try-catch blocks to handle exceptions and display detailed error messages. By wrapping the database insertion code in a try block and catching any potential exceptions in a catch block, you can log or display the error information to help diagnose and fix the issue.

try {
    // Database connection code
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    
    // Database insertion code
    $stmt = $pdo->prepare("INSERT INTO mytable (column1, column2) VALUES (?, ?)");
    $stmt->execute([$value1, $value2]);
    
    echo "Data inserted successfully!";
} catch (PDOException $e) {
    echo "Database error: " . $e->getMessage();
}