Is mysqli_real_escape_string safe?

Is this correct?

Yes. This isolated handpicked example is safe. It doesn’t mean, though, that mysqli_real_escape_string should be viewed as a function that’s purpose is to prevent SQL injections. Because in this example it protects you only by accident.

Is this a good example of how to use mysqli_real_escape_string?

Not at all

This function should be abandoned in favor of using parameters in the query. This function will fail you with any query part other than a string literal. And can be even simply overlooked.

A placeholder, also called a parameter, have to be used instead, to represent the data in your query:

$sql="SELECT * FROM usuarios WHERE username=?";
$stmt= $conn->prepare($sql);
$stmt->bind_param("s", $_POST['usuario']);
$stmt->execute();
$rs = $stmt->get_result();

See other examples in my article on the correct use of mysqli

If ever used, this function MUST be encapsulated into another function that does both escaping AND adding quotes, just like PDO::quote() does. Only this way it will be safe.

Leave a Comment