What potential SQL syntax errors can arise when using PHP to query a MySQL database?

One potential SQL syntax error that can arise when using PHP to query a MySQL database is not properly escaping user input, which can lead to SQL injection attacks. To prevent this, you should always use prepared statements or parameterized queries to safely pass user input to the database.

// Using prepared statements to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Prepare a SQL statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set parameters and execute
$username = $_POST['username'];
$stmt->execute();

// Get the result
$result = $stmt->get_result();

// Fetch data
while ($row = $result->fetch_assoc()) {
    // Output data
    echo "Username: " . $row['username'] . "<br>";
}

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