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

Darryn Smith
Darryn Smith
32,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 = 
            WHERE product_sku = ?
            ORDER BY sz_order");

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

Curtis Schrum
Curtis Schrum
9,879 Points


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.

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.

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.