What are some best practices for writing SQL queries in PHP to avoid errors?

One common issue when writing SQL queries in PHP is SQL injection attacks, where malicious code is inserted into the query. To avoid this, it's best to use prepared statements with parameterized queries. This helps to sanitize user input and prevent SQL injection vulnerabilities.

// Example of using prepared statements in PHP to avoid SQL injection

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL query with a placeholder for the user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);

// Execute the query
$stmt->execute();

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