What are common pitfalls when using PHP to access databases, such as the issue of variables in queries causing errors?

One common pitfall when using PHP to access databases is the issue of variables in queries causing errors, such as SQL injection attacks. To solve this issue, it is recommended to use prepared statements with parameterized queries, which help prevent SQL injection by separating SQL code from user input.

// Establish a database connection
$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 the parameter value to the query
$stmt->bindParam(':username', $username);

// Execute the prepared statement
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();