Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Darryn Smith32,043 Points
PDO - 'prepare' & 'bindParam' explanation?
I'm looking for an explanation of exactly what is happening under the hood when we use the ::prepare and ::bindParam methods in order to avoid SQL injection attacks.
What exactly is the object doing that prevents the attack?
On the surface, it seems to untrained eyes such as mine, that in the following code, we're still inserting the potentially dangerous user input into the query.
// assume user input of $sku... $results = $db->prepare(" SELECT size FROM products_sizes AS ps INNER JOIN sizes AS s ON ps.size_id = s.id WHERE product_sku = ? ORDER BY sz_order"); $results->bindParam(1,$sku); $results->execute();
So what exactly is going on in the ->prepare statement that makes the inclusion of $sku in the ->bindParam statement no longer dangerous?
I realize that it's not always necessary to understand WHY something works in order to use it, but I confess it makes me a little crazy when I don't...
Thanks in advance!
The easiest answer to this is we are using Prepare first to prepare the SQL. This makes it to where only SQL is taken into consideration the critical part is it returns an Object, not a string. http://www.php.net/manual/en/pdo.prepare.php
Now the bindParam method is a little different. It is a boolean it will return TRUE is the parameter given matches and is bound to the variable. Basically if it is the wrong variable type it will return False. http://us3.php.net/manual/en/pdostatement.bindparam.php
There are a few ways to explain this and I am sure someone will have a much longer way to explain it. I prefer to just focus on what the documentation says and give a simple example.
In my personal work I actually try to avoid situations where anything from user input is ever placed in a table. I also like to use EAV tables this separates out the data.