To avoid the sql injection, should I use PDO 'prepare' when querying the database, or only when updating?


Is it just as likely that I might suffer a sql injection on a query to the database (SELECT) as using UPDATE, INSERT etc?

I'm updating to PDO, so should I use 'prepare/exec' when querying the DB, or only when updating?

if you are using variable in your query (user input), either it is select query or insert/update,

like in select query you are passing variable in where clause then to prevent sql injection you should use PDO for mysql.

e.g: this is your query;

select * from login where username = '$username' and password= '$password';

then if user try to put

$username ='admin \' OR 1=1';

then compiled query will become

select * from login where username = 'admin' OR 1=1 and password= '...';

(while this ways is also wrong. you should only check for username from login table and fetch password according to user then match it through you langugae code.) but as a example select query can also injected.

See as well:

  • In PHP, how does PDO protect from SQL injections? How do prepared statements work?
  • How prepared statements can protect from SQL injection attacks?
  • How does PHP PDO's prepared statements prevent sql injection? What are other benefits of using PDO? Does using PDO reduce efficiency?
  • Can I fully prevent SQL injection by PDO Prepared statement without bind_param?
  • Are PDO prepared statements sufficient to prevent SQL injection?