What are the potential pitfalls of not properly escaping or formatting variables in PHP MySQL queries?

Not properly escaping or formatting variables in PHP MySQL queries can leave your application vulnerable to SQL injection attacks, where malicious users can manipulate the query to execute unauthorized commands on your database. To prevent this, always sanitize user input by escaping special characters before including them in your queries using functions like mysqli_real_escape_string() or prepared statements.

// Example of using prepared statements to prevent SQL injection
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

$username = mysqli_real_escape_string($mysqli, $_POST['username']);

$stmt->execute();
$result = $stmt->get_result();

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

$stmt->close();
$mysqli->close();