What are some common syntax errors in MySQL when integrating with PHP code?

One common syntax error when integrating MySQL with PHP is forgetting to escape special characters in SQL queries, which can lead to SQL injection attacks. To solve this issue, always use prepared statements or parameterized queries to safely pass user input to the database.

// Example of using prepared statements in PHP with MySQL
$conn = new mysqli($servername, $username, $password, $dbname);

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

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

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

// Get results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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