Roland
Roland

Reputation: 9691

Where to escape the string to prevent mysql injection?

I was wondering where in this code to add $stmt ->real_escape_string($password); in order to prevent mysql injection:

if ($stmt = $this->connect->prepare($sql)) {
  $stmt->bind_param('ss', $username, $password);
  $stmt->execute();
}

Is it after the prepare statement or before, because I've read that I must first have a connect statement before escaping, so my guess would be after the prepare statement, am I correct ?

And what else should I know about mysql injection ?

Upvotes: 1

Views: 165

Answers (1)

cHao
cHao

Reputation: 86506

You don't.

Part of what prepared statements do, is escape the data for you. So you don't need to escape anything if you're binding it as a param. In fact, if you did add it, you'd see backslashes and such in odd places.

The only time you'd need to use real_escape_string, is when you're inserting variables directly into your SQL string as values. And if someone's doing that, they may want to double-check their understanding of the whole point of prepared statements. :)

Upvotes: 3

Related Questions