What is the purpose of using mysql_escape_string() in PHP and what potential pitfalls can arise from its usage?

The purpose of using `mysql_escape_string()` in PHP is to escape special characters in a string before sending a query to the MySQL database. This helps prevent SQL injection attacks by ensuring that user input is properly sanitized. However, `mysql_escape_string()` is deprecated in newer versions of PHP and has been replaced by `mysqli_real_escape_string()` or prepared statements due to potential pitfalls such as not being able to handle all types of characters properly.

// Deprecated: mysql_escape_string() usage
$input = $_POST['user_input'];
$escaped_input = mysql_escape_string($input);
$query = "SELECT * FROM users WHERE username='$escaped_input'";
$result = mysql_query($query);
```

To fix this issue and use `mysqli_real_escape_string()` instead, the code snippet below should be used:

```php
// Correct: mysqli_real_escape_string() usage
$input = $_POST['user_input'];
$escaped_input = mysqli_real_escape_string($connection, $input);
$query = "SELECT * FROM users WHERE username='$escaped_input'";
$result = mysqli_query($connection, $query);