Are there best practices for formatting SQL queries within PHP to prevent syntax errors?

When embedding SQL queries within PHP code, it is essential to properly format the queries to prevent syntax errors. One common practice is to use prepared statements with placeholders for variables to avoid SQL injection attacks and ensure proper escaping of values. Additionally, using functions like mysqli_real_escape_string() can help sanitize user input before including it in the query.

// Example of using prepared statements to prevent syntax errors in SQL queries
$mysqli = new mysqli("localhost", "username", "password", "database");

// Prepare the SQL statement with placeholders
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind parameters to the placeholders
$stmt->bind_param("s", $username);

// Set the parameter values
$username = "john_doe";

// Execute the query
$stmt->execute();

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

// Process the results
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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