What are common syntax errors in PHP when executing MySQL queries and how can they be avoided?

One common syntax error in PHP when executing MySQL queries is forgetting to properly escape strings before inserting them into the query. This can lead to SQL injection attacks. To avoid this, it's recommended to use prepared statements with placeholders for dynamic values.

// Example of using prepared statements to avoid SQL injection

// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Prepare the statement with a placeholder for the dynamic value
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set the dynamic value and execute the query
$username = "john_doe";
$stmt->execute();

// Fetch the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Process the results
}

// Close the statement and connection
$stmt->close();
$mysqli->close();