Why is it important to escape values before inserting them into SQL queries in PHP?

It is important to escape values before inserting them into SQL queries in PHP to prevent SQL injection attacks. By escaping values, special characters are properly handled, preventing them from being interpreted as part of the SQL query. This helps to ensure the security and integrity of the database.

// Example of escaping values before inserting them into an SQL query
$connection = new mysqli("localhost", "username", "password", "database");

// Assume $user_input contains the user input to be inserted into the database
$user_input = "John Doe";

// Escape the user input before inserting it into the SQL query
$escaped_user_input = $connection->real_escape_string($user_input);

// Construct and execute the SQL query with the escaped value
$query = "INSERT INTO users (name) VALUES ('$escaped_user_input')";
$connection->query($query);