I’m using mysqli extension in php for connection to database. I’ve such a simple question. Is it better to use mysqli instead of mysql and why is it necessary to use mysqli_real_escape_string ? what is this function doing exactly ? Thanks …
Share
I’ll put a little example not using SQL. Imagine you have this PHP code:
Now you want to replace
worldwithO'Hara:Yeah, of course, that is not valid PHP. You need to escape the single quote since it’s interpreted as a literal quote rather than the string delimiter:
You have exactly the same problem when composing SQL queries. If you inject random input into your code, sooner or later it’ll break. You need to encode input so it’s handled as literal input rather than broken code.
How can you do that? Well, MySQL accepts
\'just like PHP (though it’s only a coincidence: other database engines use other escape methods). So the dumbest solution is to add back slashes here and here:Of course, it’s a lot of work to hard-code all the possible characters that need escaping (and you’ll probably forget some of them) so you can use a function that does the job for you: either
mysql_real_escape_string()ormysqli_real_escape_string().The question is: is this good enough? Well, it kind of works, but it leads to annoying code that’s difficult to maintain:
… and you still need to take care of surrounding the complete value with single quotes… which are not always mandatory (think of numbers)… What a mess. Can’t someone invent something better? Good news is: they did! It’s called prepared statements:
In real life:
prepare()method to accomplish this. Find some examples there.I hope this explains the whole question.