alee
alee

Reputation: 53

Prepared statements and "real escape string"

I have read on this site that when using prepared statements i do not need to use real_escape_string. I am new to prepared statements. I created a prepared statement that passes string.

 $stmt = $conn->prepare("INSERT INTO `messages` (`topic`, `message`,         `user`)VALUES(?, ?, ?)");
 $stmt->bind_param("sss", $topic, $message, $user);

Then I input this string into any of the fields: { /n \n /r \r " I'm cooking" ' } (stuff inside the brackets.) That is what shows up exactly in the database. However if I add a real_escape_string, I get { /n \\n /r \\r \" I\'m cooking\" \' }

So I'm confused, real_escape_string is definitely changing the input, do I need it, or is /n /r just fine?

Upvotes: 0

Views: 788

Answers (2)

deceze
deceze

Reputation: 522032

Well, yes, real_escape_string is changing the values, that's its job. It changes values in a way that they will be valid SQL string literals when placed in quotes.

However, prepared statements avoid the whole issue of "string literals in quotes", you don't have to worry about it at all. Prepared statements will take any string and ensure that it's inserted into the database as is without either becoming malformed or producing syntax issues due to it being evaluated as a string literal. And that's exactly what you're seeing: your values are inserted into the database exactly as you provide them, which is exactly what you'd want.

You do not need real_escape_string when using prepared statements with value binding.

Read this: The Great Escapism (Or: What You Need To Know To Work With Text Within Text).

Upvotes: 2

psx
psx

Reputation: 4048

You do not need real_escape_string when using prepared statements. In fact, no escaping of input data is needed.

You cannot escape out of a prepared statement value.

You are correct when you say real_escape_string is changing the value. This is because if you were not using prepared statements, you would need to escape the data. So, real_escape_string performs the escaping required and provides the output you are seeing (\\n etc). As explained, this process is not needed for prepared statements.

Upvotes: 0

Related Questions