Why is it recommended to use mysql_real_escape_string() to escape values before sending them to the database in PHP?

It is recommended to use mysql_real_escape_string() to escape values before sending them to the database in PHP to prevent SQL injection attacks. This function escapes special characters in a string, making it safe to use in SQL queries. By using this function, you can ensure that user input is properly sanitized before being inserted into the database, reducing the risk of malicious code execution.

// Example of using mysql_real_escape_string() to escape values before sending them to the database

// Assuming $conn is the database connection object

// Retrieve user input
$user_input = $_POST['user_input'];

// Escape the user input
$escaped_input = mysql_real_escape_string($user_input);

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

// Check if the query was successful
if($result) {
    echo "Data inserted successfully";
} else {
    echo "Error inserting data: " . mysqli_error($conn);
}