What are common pitfalls to avoid when writing PHP code to interact with a MySQL database?

One common pitfall to avoid when writing PHP code to interact with a MySQL database is using insecure methods to prevent SQL injection attacks. To avoid this, always use prepared statements with parameterized queries to sanitize user input before executing SQL queries.

// Connect to MySQL database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind parameters and execute the query
$username = $_POST['username'];
$stmt->bindParam(':username', $username);
$stmt->execute();

// Fetch results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);