PHP’s mysqli, and mysqli_real_escape_string()

I used to use $newValue = addslashes($newValue) when inserting data into MySQL and $currentValue = stripslashes($currentValue) when pulling it out. Then a week or so ago, I discovered mysqli_real_escape_string().

Seriously, start using it because then you don’t have to ever do $currentValue = stripslashes($currentValue) when pulling data out.

Here’s the procedural way of doing it (just took it right out of the docs):
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$newValue = mysqli_real_escape_string($link, $newValue);

And here’s the object oriented way of doing it (less verbiose and just as clear — I prefer this method).
$db = new mysqli("localhost", "my_user", "my_password", "world");
$newValue = $db->real_escape_string($newValue);

The only thing that bothers me is that there is no reason they couldn’t just have called the function mysqli_escape (.. crossed out just incase.) I mean really, that’s one of those functions that there is no way out of having to use it (at times) every line for 20 lines of code.

Leave a Reply