Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysqli_real_escape_string, should I use it?

Tags:

php

mysqli

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'])
like image 319
dontHaveName Avatar asked Dec 23 '12 14:12

dontHaveName


People also ask

Do I need mysqli_real_escape_string?

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 ...

Is mysqli_real_escape_string secure?

Yes. This isolated handpicked example is safe.

Does mysqli_real_escape_string prevent SQL injection?

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.

What does mysqli_real_escape_string mean?

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.


1 Answers

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

  • How can I prevent SQL injection in PHP?
like image 184
Mark Byers Avatar answered Oct 28 '22 11:10

Mark Byers