Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reasons to strongly type parameters in PDO?

Tags:

php

pdo

When you bind parameters to SQL statement, you can provide parameter type like PDO::PARAM_STR. If you don't, type defaults to PDO::PARAM_STR. What can be the reasons to specifically set the type of each parameter? PDO::PARAM_STR works with any parameter as I know at least in MySQL. I think even with PDO::PARAM_STR can be used even with BLOB columns.

PDO::PARAM_STR does not introduce any SQL injection because you still have prepared queries.

like image 647
Vladislav Rastrusny Avatar asked Apr 26 '11 16:04

Vladislav Rastrusny


People also ask

What is PDO parameter binding?

The PDOStatement::bindParam() function is an inbuilt function in PHP that is used to bind a parameter to the specified variable name.

What is prepared statements in PDO?

In layman's terms, PDO prepared statements work like this: Prepare an SQL query with empty values as placeholders with either a question mark or a variable name with a colon preceding it for each value. Bind values or variables to the placeholders. Execute query simultaneously.

Does PDO prevent SQL injection?

Also, calling PDO::prepare() and PDOStatement::execute() helps to prevent SQL injection attacks by eliminating the need to manually quote and escape the parameters.

What is PDO :: Param_str?

PDO::PARAM_STR. Represents SQL character data types. For an INOUT parameter, use the bitwise OR operator to append PDO::PARAM_INPUT_OUTPUT to the type of data being bound. Set the fourth parameter, length , to the maximum expected length of the output value.


2 Answers

Using PARAM_STR happens to always work in column values because mySQL implicitly converts values to the correct type where it can, but it will fail for example in this query:

$limit = 1;

$dbh->prepare("SELECT * FROM items LIMIT :limit");
$dbh->bindParam(":limit", $limit, PDO::PARAM_STR); 
     // Will throw "You have an error in your SQL syntax..."

one should absolutely use PARAM_INT where appropriate - for cases like the one above, and to prepare for database engines other than mySQL that may be more strict in what they expect.

like image 189
Pekka Avatar answered Nov 15 '22 17:11

Pekka


personally I see no reason, as long as you have this attribute set:

$dbh->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );

so, it would detect LIMIT case automatically

anyway I'd prefer to define type in a placeholder, not in binding function.

However, my experience with PDO is not that strong. I just tried it out and decided to turn back to plain mysql.

like image 40
Your Common Sense Avatar answered Nov 15 '22 18:11

Your Common Sense