What are the potential pitfalls of not properly escaping values when executing SQL queries in PHP?

Not properly escaping values when executing SQL queries in PHP can lead to SQL injection attacks, where malicious SQL code is inserted into input fields to manipulate the database. To prevent this, always use prepared statements with parameterized queries or escape input values using functions like mysqli_real_escape_string().

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

if ($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()) {
        // Do something with the data
    }
    
    $stmt->close();
}

$mysqli->close();