Is it necessary to establish a connection with MySQL before using mysql_real_escape_string in PHP?

Yes, it is necessary to establish a connection with MySQL before using mysql_real_escape_string in PHP. This function requires an active MySQL connection in order to properly escape special characters in a string to prevent SQL injection attacks. To establish a connection with MySQL, you can use the mysqli_connect function to connect to the database server.

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

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Use mysql_real_escape_string to escape special characters
$escaped_string = mysqli_real_escape_string($connection, $unescaped_string);

// Close the connection
mysqli_close($connection);