Is mysqli_real_escape_string safe?

Solution 1:

Is this correct?

Yes.

Is this a good example of how to use mysqli_real_escape_string?

NO

If ever used, this function have to be encapsulated into some inner processing, and never have to be called right from the application code. A placeholder have to be used instead, to represent data in your query:

$sql='SELECT * FROM usuarios WHERE username=? AND pass=?';

And then, upon processing placeholder marks, this function may be applied (if applicable) but not by itself but along ALL the formatting rules.

Solution 2:

Yes you will use it save now.

The nice thing about using mysqli is that it is Object oriented. So you can use it like this:

<?php

$mysqli = new mysqli("host", "user", "password", "database");

$usuario = $mysqli->real_escape_string($_POST["usuario"]);
$clave = $mysqli->real_escape_string($_POST["clave"]);

$sql='  SELECT * FROM usuarios 
        WHERE username="'.$usuario.'" 
        AND pass="'.$clave.'"
     ';

$mysqli->query($sql);

$mysqli->close();
?>

Or you can use PDO.

Solution 3:

The use of mysqli() functions should only be reserved for framework developers and others who are aware of all the safety issues it can bring. For everyone else, there's PDO. It's just as easy to use as mysqli(), and far safer.