Mysql_real_escape_string for POST

I have 2 POST values in an action page.
The one is _POST['title'] and the other is _POST[‘contents’].

Before inserting or updating the database “mySQL” with any POST values, should I always use mysql_real_escape function for any POST values like the following?

$title=mysql_real_escape_string($_POST['title']);
$contents=mysql_real_escape_string($_POST['contents']);

What you need to do is stop using dangerous obsolete MySQL code that has been completely removed from PHP. You need to use PDO with prepared statements.

3 Likes

Following on from Benamens post, i agree you should be definitely using prepared statements.

I was in the same boat & Benamen recommended that I switch to PDO or OOP. Whilst it wasn’t the ideal solution as I was mid project, I continued with the project in procedural. Learning OOP now I wish I had taken the advice & switched sooner. Don’t get me wrong I’ve only just scratched the surface of OOP but the layout of the code is so much cleaner and will make your life a lot easier as the project scales.

3 Likes

Thank you for your advice, benanamen and oli_d111.
I’ll keep that in my mind and I’ll use PDO on the next major version up of my project.
Sorry to say I have to use the old way for some time( I guess it will take some months)

Too vague a statement.

You should always validate and sanitize your user input variables, yes. mysql(i)_real_escape_string is not always the right answer.
If your variable is a number, sanitize it as such. If your variable is a date, make sure it’s in a date format.

This is true regardless of whether you’re using PDO/Prepared Statements or not (which you should.)

validate and sanitize, Thank you.

An acronym that is used a lot in this context is FIEO:

Filter Input, Escape Output

So make sure you filter everything that is supplied by users, assume all users have malicious intent. Then, act as if they succeeded getting malicious data in anyway, and escape the output to make sure their attack doesn’t work.

1 Like

The old mysql_* extension hat you’ve used was REMOVED from PHP as of PHP version 7.0 so if your code ends up on any server running version 7.0 of PHP or newer it’ll be broken. PDO has been around for a good few years and should be available to you.

1 Like