What common syntax errors can occur in PHP scripts, particularly when handling database queries like in the provided code snippet?

One common syntax error when handling database queries in PHP scripts is forgetting to properly escape variables before including them in the query. This can lead to SQL injection vulnerabilities and syntax errors. To solve this issue, it is recommended to use prepared statements with parameterized queries to safely pass variables to the database.

// Incorrect way without using prepared statements
$unsafe_variable = $_POST['user_input'];
$query = "SELECT * FROM users WHERE username = '$unsafe_variable'";
$result = mysqli_query($connection, $query);

// Correct way using prepared statements
$safe_variable = mysqli_real_escape_string($connection, $_POST['user_input']);
$query = "SELECT * FROM users WHERE username = ?";
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, "s", $safe_variable);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);