PDO prepare statements

Can I just get clarification on this, just a discussion that I have:

Using this as an example:

$conn->prepare ( 'SELECT * FROM table WHERE id = "' . $_POST['id'] . '"' ); 

Does SQL injection help prevent, do you need to bind parameters or misinform values ​​before inserting into a preparation statement? Or am I mistaken, and is this normal, just use cooking?

+4
source share
3 answers

Prepared statements use placeholders for the values ​​to be inserted. The code snippet in your question already interpolates the value in the query and is therefore subject to SQL injection.

The following pseudo-code highlights prepared statements:

 $stmt = $conn->prepare('SELECT * FROM `table` WHERE `id` = ?'); $stmt->execute($_POST['id']); 

In this example, the logic of this "code" will take care of correctly quoting what is in $_POST['id'] , and substituting a question mark ? in it. You may also encounter the following placeholders:

 $stmt = $conn->prepare('SELECT * FROM `table` WHERE `id` = :id'); $stmt->execute(array( 'id' => $_POST['id'] )); 

Please note, however, that the prepared statements do not relieve you of the obligation to check the user input provided before passing it to the (My) SQL statement: if id expected to be integer, only accept integers as input.

+5
source

Yes, this does not prevent SQL injection, you should use

$conn->prepare ( 'SELECT * FROM table WHERE id = ?' );

+2
source

That's right, you need to bind parameters to take advantage of PDO sql injection protection.

And remember that PDO does not add htmlspecialchars, so if this is important to you, you must do it yourself.

0
source

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


All Articles