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.
The PDOStatement::bindParam() function is an inbuilt function in PHP that is used to bind a parameter to the specified variable name.
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.
Also, calling PDO::prepare() and PDOStatement::execute() helps to prevent SQL injection attacks by eliminating the need to manually quote and escape the parameters.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With