What are some tips for avoiding errors in PHP scripts, especially when dealing with fetching and using data from a database?

When dealing with fetching and using data from a database in PHP scripts, it's important to handle errors properly to ensure the script runs smoothly. One common error to avoid is not checking for database connection errors before executing queries. To prevent this, always use try-catch blocks when connecting to the database and executing queries. Additionally, sanitize user input to prevent SQL injection attacks.

try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Fetch data from the database
    $stmt = $pdo->prepare("SELECT * FROM mytable");
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Use the fetched data
    foreach ($result as $row) {
        echo $row['column_name'] . "<br>";
    }
    
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}