What are the best practices for passing variables in SQL queries in PHP to avoid errors?

When passing variables in SQL queries in PHP, it is important to use parameterized queries to prevent SQL injection attacks and errors. This can be done by using prepared statements with placeholders for the variables, which are then bound to the actual values before executing the query. This ensures that the variables are properly sanitized and escaped, making the query safe and secure.

// Example of passing variables in SQL queries using parameterized queries

// Assuming $conn is the database connection object

// Define the SQL query with placeholders for variables
$sql = "SELECT * FROM users WHERE username = :username";

// Prepare the statement
$stmt = $conn->prepare($sql);

// Bind the variable to the placeholder
$stmt->bindParam(':username', $username, PDO::PARAM_STR);

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

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