How can error handling be improved in PHP scripts that interact with a MySQL database to troubleshoot issues like data not being added to the database?

When data is not being added to a MySQL database in PHP scripts, it is important to implement proper error handling to troubleshoot the issue. One way to improve error handling is to use try-catch blocks to catch any exceptions that may occur during the database interaction process. This allows for more detailed error messages to be displayed, helping to identify the root cause of the problem.

try {
    // Connect to the MySQL database
    $conn = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Prepare and execute the SQL query to insert data into the database
    $stmt = $conn->prepare("INSERT INTO myTable (column1, column2) VALUES (:value1, :value2)");
    $stmt->bindParam(':value1', $value1);
    $stmt->bindParam(':value2', $value2);
    $stmt->execute();

    echo "Data added successfully";
} catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}