Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Using PHP with MySQL Using Relationship Tables in MySQL Displaying Shirt Sizes

Darryn Smith
Darryn Smith
32,043 Points

PDO - 'prepare' & 'bindParam' explanation?

Hi.

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!

1 Answer

Darryn,

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.