What are the differences between using mysql_query and mysql_real_escape_string in PHP, and when should each be used?

When working with user input in PHP and MySQL, it is important to sanitize the input to prevent SQL injection attacks. The `mysql_query` function is used to execute SQL queries directly, while `mysql_real_escape_string` is used to escape special characters in a string to make it safe for use in a SQL query. `mysql_real_escape_string` should be used to sanitize user input before using it in a query to prevent SQL injection attacks.

// Using mysql_real_escape_string to sanitize user input before using it in a 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);