How does this PDO code protect against SQL injection?

So, I studied all this PDO thing, and I read this blog tutorial when I came across this code, and the explanation was that if I use PDO with data binding, users will not be able to add SQL injections. How it works?

  # no placeholders - ripe for SQL Injection!  
 $ STH = $ DBH -> ("INSERT INTO folks (name, addr, city) values ​​($ name, $ addr, $ city)");  

 # unnamed placeholders  
 $ STH = $ DBH -> ("INSERT INTO folks (name, addr, city) values ​​(?,?,?); 

 # named placeholders 
 $ STH = $ DBH -> ("INSERT INTO folks (name, addr, city) value (: name,: addr,: city)");  

Here is a link to the site that I received from you, you want to read for reference. http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

+4
source share
5 answers

(There is an error in the 2nd line, the line is not completed. Add "); at the end, and everything will be fine. This is on the page with which you are connected, so this is their fault. Of course, you must specify the values ​​that will replace the question marks and then actually run the query before you get any results.)

In any case, to the point. PDO looking for markers ? or :name and replaces them (in order or by name, respectively) with the values ​​you specify. When values ​​are inserted into the query string, they are first processed to avoid anything that can be used for injection attacks.

This is similar to using the mysql_real_escape_string() (or weaker addslashes() ) value before using it in the query, but PDO does this automatically and better on it.

+3
source

PDO does much more backstage than just replacing your placeholders with parameterized data. Database engines can accept queries in a form similar to "here is your expression, here are placeholders, and I will tell you what happens in each placeholder." The SQL engine knows that parameters are NOT raw code that must be executed, but processed only as data.

+4
source

Because PDO knows how to correctly insert values ​​into a query when you use a prepared statement.

0
source

When you bind a value to a placeholder, for example

 $sth->bindValue(':name', $name, PDO::PARAM_STR); 

PDO will take care to avoid it. Therefore, SQL Injections will not work.

0
source

Since a prepared statement with binding parameters is an operator in which the analysis of the request has already been performed, and there can only be striongs or ints for string or ints. No new analysis of statements is performed, so no arguments can be parsed as something related to SQL, and will never be parsed as SQL.

0
source

Source: https://habr.com/ru/post/896848/


All Articles