I want to eliminate sql injection, should I use mysqli_real_escape_string()
or is it clear in mysqli?
For example
$nick = mysqli_real_escape_string($_POST['nick'])
You should use mysqli_real_escape_string for any data that comes from the user or can't be trusted. Show activity on this post. You have to use it when you include $_REQUEST "vars" in your query eg. each of this querys must be mysqli_real_escape_string to provide injections ...
Yes. This isolated handpicked example is safe.
No. As uri2x says, see SQL injection that gets around mysql_real_escape_string() . The best way to prevent SQL injection is to use prepared statements.
The real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in an SQL query, taking into account the current character set of the connection. This function is used to create a legal SQL string that can be used in an SQL statement.
You should use prepared statements and pass string data as a parameter but you should not escape it.
This example is taken from the documentation:
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
Note that the example does not call mysqli_real_escape_string
. You would only need to use mysqli_real_escape_string
if you were embedding the string directly in the query, but I would advise you to never do this. Always use parameters whenever possible.
Related
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With