PDO防注入原理分析以及注意事项
我们都知道,只要合理正确使用PDO,可以基本上防止SQL注入的产生,本文主要回答以下两个问题:
为什么要使用PDO而不是mysql_connect?
为何PDO能防注入?
使用PDO防注入的时候应该特别注意什么?
一、为何要优先使用PDO?
PHP手册上说得很清楚:
Preparedstatementsandstoredprocedures Manyofthemorematuredatabasessupporttheconceptofpreparedstatements.Whatarethey?TheycanbethoughtofasakindofcompiledtemplatefortheSQLthatanapplicationwantstorun,thatcanbecustomizedusingvariableparameters.Preparedstatementsoffertwomajorbenefits:
Thequeryonlyneedstobeparsed(orprepared)once,butcanbeexecutedmultipletimeswiththesameordifferentparameters.Whenthequeryisprepared,thedatabasewillanalyze,compileandoptimizeitsplanforexecutingthequery.Forcomplexqueriesthisprocesscantakeupenoughtimethatitwillnoticeablyslowdownanapplicationifthereisaneedtorepeatthesamequerymanytimeswithdifferentparameters.Byusingapreparedstatementtheapplicationavoidsrepeatingtheanalyze/compile/optimizecycle.Thismeansthatpreparedstatementsusefewerresourcesandthusrunfaster.
Theparameterstopreparedstatementsdon'tneedtobequoted;thedriverautomaticallyhandlesthis.Ifanapplicationexclusivelyusespreparedstatements,thedevelopercanbesurethatnoSQLinjectionwilloccur(however,ifotherportionsofthequeryarebeingbuiltupwithunescapedinput,SQLinjectionisstillpossible).