What are the common pitfalls when accessing MySQL tables in PHP and how can they be avoided?
Common pitfalls when accessing MySQL tables in PHP include not sanitizing user input before using it in queries, not handling errors properly, and not closing the database connection after use. To avoid these pitfalls, always use prepared statements to prevent SQL injection, check for errors after executing queries, and close the database connection when finished.
// Example of using prepared statements to avoid SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
```
```php
// Example of checking for errors after executing queries
$result = $pdo->query("SELECT * FROM users");
if($result === false){
die('Error executing query');
}
```
```php
// Example of closing the database connection after use
$pdo = null;