mysqli_real_escape_string()
is no longer the best way to ensure the data you save in your database is safe. Instead, you should be using prepared statements: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
As to your question: Anytime you are putting data that you are unsure of (especially if that data comes from unknown sources like a web form) into your database you should be making sure that it is properly formatted for your database. mysqli_real_escape_string()
can only do that for string literals which is why prepared statements are the better approach. Anytime you execute a query that relies on user submitted data, you should be using prepared statements.
When you output data to display to the user, you don't need to use mysqli_real_escape_string(), but should instead be escaping for the web using htmlspecialchars()
(http://php.net/htmlspecialchars)
situation 1 - YES DEFINITELY, and even better would be to use prepared statements.
situation 2 - If you are displaying data to the user on a web page, you do not need to use mysqli_real_escape_string()
but should instead use htmlspecialchars()
to decrease the risk of XSS and other code injection attacks.
A few examples:
<?php
// Prepared statement. Save the user's first name to the database:
$stmt = $mysqli->prepare("INSERT INTO users(first_name) VALUES (?)");
$stmt->bind_param("s", $first_name);
$stmt->execute();
// Echo the user's first name back to them
echo "Saved your first name: " .
htmlspecialchars($first_name) . " to the database.";
For more information on preventing SQL injection, see this excellent answer: How can I prevent SQL injection in PHP?