What are the potential pitfalls of not properly sanitizing user input before executing SQL queries in PHP?

If user input is not properly sanitized before executing SQL queries in PHP, it can lead to SQL injection attacks where malicious code is injected into the query, potentially exposing sensitive information or allowing unauthorized access to the database. To prevent this, it is important to use prepared statements with parameterized queries or escape user input using functions like mysqli_real_escape_string.

// Sanitize user input using mysqli_real_escape_string
$user_input = mysqli_real_escape_string($connection, $_POST['user_input']);

// Prepare and execute a parameterized query
$stmt = $connection->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $user_input);
$stmt->execute();
$result = $stmt->get_result();

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

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