What are the differences between mysqli_real_escape_string and mysql_real_escape_string functions in PHP, and how should they be used effectively?

The main difference between mysqli_real_escape_string and mysql_real_escape_string functions in PHP is that mysqli_real_escape_string is used for escaping strings when using the MySQLi extension, while mysql_real_escape_string is used for escaping strings when using the deprecated MySQL extension. It is recommended to use mysqli_real_escape_string as it is more secure and up-to-date. To use mysqli_real_escape_string effectively, you should always pass the database connection object as the first argument to the function.

// Create a database connection
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check for connection errors
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Escape a string using mysqli_real_escape_string
$string_to_escape = "Some string with 'special' characters";
$escaped_string = $mysqli->real_escape_string($string_to_escape);

// Use the escaped string in a query
$query = "INSERT INTO table_name (column_name) VALUES ('$escaped_string')";
$mysqli->query($query);

// Close the database connection
$mysqli->close();