$dbh->prepare()
already does the escaping for you. There is a PDO function PDO::quote()
to escape strings independently from the prepare method but as the doc says:
If you are using this function to build SQL statements, you are
strongly recommended to use PDO::prepare() to prepare SQL statements
with bound parameters instead of using PDO::quote() to interpolate
user input into an SQL statement. Prepared statements with bound
parameters are not only more portable, more convenient, immune to SQL
injection, but are often much faster to execute than interpolated
queries, as both the server and client side can cache a compiled form
of the query.
The use of htmlspecialchars()
is unnecessary, when you are printing content from the database. The point of escaping is to prevent SQL Injections as you correctly noted. But these injections can only happen within your sql statement and only if (as Ohgodwhy mentioned) userinput from $_POST
or $_GET
or whaterver the user can manipulate is part of your query.