What is the role of mysql_real_escape_string() in PHP and how does it help prevent security risks?

The role of mysql_real_escape_string() in PHP is to escape special characters in a string to prevent SQL injection attacks. This function helps prevent security risks by ensuring that user input is sanitized before being used in SQL queries, thus preventing malicious SQL code from being injected into the query.

// Example of using mysql_real_escape_string() to prevent SQL injection
$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);