views:

104

answers:

2

Possible Duplicate:
Do I have to use mysql_real_escape_string if I bind parameters?

I have a quick MySQLi security related question...

For example, take a look at this code (gets input from the user, checks it against the database to see if the username/password combination exist):

$input['user'] = htmlentities($_POST['username'], ENT_QUOTES);
$input['pass'] = htmlentities($_POST['password'], ENT_QUOTES);

// query db
if ($stmt = $mysqli->prepare("SELECT * FROM members WHERE username=? AND password = ?"))
{
    $stmt->bind_param("ss", $input['user'], md5($input['pass'] . $config['salt']));
    $stmt->execute();
    $stmt->store_result();

    // check if there is a match in the database for the user/password combination
    if ($stmt->num_rows > 0)
    {}
}

In this case, I am using htmlentities() on the form data, and using a MySQLi prepared statement. Do I still need to be using mysql_real_escape_string()?

+1  A: 

Yes since there are non html related entities that can cause harm to your database that real escape string catches. Like UTF-8 characters.

But as noted here in the comments you are using mysqli prepare and that is enough.

BTW MySQLi has it's own escape string function. if you are interested.

Ólafur Waage
Won't using a prepared statement fix that though? The `htmlentities()` call seems unnecessary, honestly; I'm not sure why he did it, unless it's for a non-database reason
Michael Mrozek
Sorry yea didnt see the prepare there. Yes it is correct.
Ólafur Waage
if I'm displaying the $_POST data back out on the page, using htmlentities() makes sense, correct?But if I'm just using the $_POST data within the MySQLi query, MySQLi will automatically escape everything?
Benjamin Falk
@Ben Yes, it's intended to be used when you're sending displayed text to the client. Prepared statements escape everything automatically, you don't need to do anything extra; that's one of the main benefits of using them
Michael Mrozek
Ah, thanks for the clarification.
Benjamin Falk
Mr Waage is correct MySQLi doesn't handle UTF-8 characters, if you keep the encoding default for your client (should be latin1) then you have nothing to worry about. Also the htmlentities is redundant, it should be called before output, not before authentication as it changes the value of the username/password.
Rook
+1  A: 

No, you do not need to use mysql_real_escape_string if you are binding the parameters using prepared statements. In fact using it will give you the wrong result as the escaped data will be inserted into the database. mysql_real_escape_string is needed when the parameter is written directly into the SQL string without using parameters.

Mark Byers