What common syntax errors can occur in PHP when writing SQL queries?

One common syntax error that can occur in PHP when writing SQL queries is forgetting to properly escape variables to prevent SQL injection attacks. To solve this issue, you should use prepared statements with parameterized queries instead of directly interpolating variables into the SQL query string.

// Incorrect way without escaping variables
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql);

// Correct way using prepared statements
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();