When should mysql_real_escape_string be used in PHP programming?

mysql_real_escape_string should be used in PHP programming when inserting user input into a MySQL database to prevent SQL injection attacks. This function escapes special characters in a string to make it safe for use in SQL queries. It helps to protect your database from malicious input that could manipulate or retrieve sensitive information.

// Assuming $conn is the MySQL database connection object
$user_input = $_POST['user_input']; // User input from a form
$escaped_input = mysqli_real_escape_string($conn, $user_input);

// Insert the escaped input into the database
$sql = "INSERT INTO table_name (column_name) VALUES ('$escaped_input')";
mysqli_query($conn, $sql);