What is the purpose of using mysql_real_escape_string in PHP scripts and where should it be implemented for security?

When dealing with user input in PHP scripts, it is important to sanitize the data to prevent SQL injection attacks. One way to do this is by using the mysql_real_escape_string function, which escapes special characters in a string to make it safe for use in a SQL query. It should be implemented whenever user input is being used in a SQL query to ensure the security of the application.

// Example of using mysql_real_escape_string to sanitize user input in a SQL query
$user_input = $_POST['user_input'];
$escaped_input = mysql_real_escape_string($user_input);

$query = "SELECT * FROM users WHERE username = '$escaped_input'";
$result = mysql_query($query);