Why is it important to properly sanitize user input before using it in SQL queries in PHP?

It is important to properly sanitize user input before using it in SQL queries in PHP to prevent SQL injection attacks. SQL injection attacks occur when malicious users input SQL code into form fields, which can then be executed by the database, potentially leading to data loss or unauthorized access. To prevent this, user input should be sanitized to escape special characters that could be interpreted as SQL code.

// Sanitize user input before using it in an SQL query
$user_input = $_POST['user_input']; // Assuming user input is coming from a POST request

// Sanitize the user input using mysqli_real_escape_string
$sanitized_input = mysqli_real_escape_string($connection, $user_input);

// Use the sanitized input in your SQL query
$query = "SELECT * FROM users WHERE username = '$sanitized_input'";
$result = mysqli_query($connection, $query);

// Remember to establish a database connection before using mysqli_real_escape_string