2
votes

I am using PDO to users input, but right now I'm not using PDO when displaying content from my MySQL database (still the old fashioned way with SQL commands..).

Is it necessary to filter/sanitiza inputs from users when inserting data to a MySQL database?

AND, if the way to go is to sanitize the output instead, then what is the best way to sanitize output? Am I good to go, if I just use htmlspecialchars() or do i need to use strip_tags() and other things also?

I am using placeholders and prepared statements.

Thank you.

2

2 Answers

6
votes

You're confusing different sanitizing here :

  • The SQL sanatizing for data to insert to your DB. With prepared query with params, no need to escape, PDO do it internally. If you don't use prepared queries, use them. It's bullet-proof (as far as I know).

  • The data you get from your DB and output as HTML : here you have to sanatize before printing it to your user (to prevent XSS), either by using htmlspecialchars() , htmlentites() or strip_tags(), depending what you want to escape or delete.

5
votes

If you're properly using parameterized queries, then no, you don't have to escape. That'd actually insert escaped data into the database, so you'd get the escapes coming back our later when you select the data.

However, just switching to PDO does NOT make your code any safer, e.g. if you do

$sth = $db->prepare("INSERT INTO sometable (x) VALUES ($_GET[x])");

is still utterly vulnerable to injections attacks, since you're not using placeholders.