Why is it important to consider context switching and use mysqli_real_escape_string() when inserting values into SQL queries in PHP?

Context switching is important to consider because it ensures that the data being inserted into SQL queries is properly sanitized to prevent SQL injection attacks. Using mysqli_real_escape_string() function helps escape special characters in a string for use in an SQL statement, reducing the risk of malicious code being injected into the query.

// Example code snippet demonstrating the use of mysqli_real_escape_string() to prevent SQL injection

// Establish a database connection
$connection = mysqli_connect("localhost", "username", "password", "database");

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

// Escape the user input using mysqli_real_escape_string()
$escaped_input = mysqli_real_escape_string($connection, $user_input);

// Insert the sanitized data into the database
$query = "INSERT INTO users (name) VALUES ('$escaped_input')";
mysqli_query($connection, $query);

// Close the database connection
mysqli_close($connection);