While introducing myself to pgSQL prepared statements, I’ve successfully returned the results of a few queries. However, I have a few questions.
Given the following query:
$w_ft = "36";
$sth = $dbh->prepare("SELECT * FROM main_products_common_dimensions WHERE w_ft = :w_ft");
$sth->bindParam(':w_ft', $theId, PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetchAll();
I notice that even though the column in the main_products_common_dimensions table is a character_varying, I get the same/correct result set returned if I use
$w_ft = 36;
...
$sth->bindParam(':w_ft', $w_ft, PDO::PARAM_INT);
and
$w_ft = "36";
...
$sth->bindParam(':w_ft', $w_ft, PDO::PARAM_STR);
and
$w_ft = "36";
...
$sth->bindParam(':w_ft', $w_ft, PDO::PARAM_INT);
and
$w_ft = 36;
...
$sth->bindParam(':w_ft', $w_ft, PDO::PARAM_STR);
That is, no matter how I bind the parameter _INT or _STR or set the variable (integer or string), the data is returned correctly. Is this normal behavior?
From http://php.net/manual/en/pdostatement.bindparam.php, I see that the parameter datatype is explained
Explicit data type for the parameter using the PDO::PARAM_* constants.
To return an INOUT parameter from a stored procedure, use the bitwise
OR operator to set the PDO::PARAM_INPUT_OUTPUT bits for the data_type
parameter.
What is meant by “returning an INOUT parameter from a stored procedure”? Is this related? Does that imply that I am not using a stored procedure? Length seems to be optional, though that is not indicated in its explanation. Are there advantages to providing it?
As you can see, I’m quite new to this, and just trying to get my head around it. Thank you very much
PDO::PARAM_INTandPDO::PARAM_STRwhen passed tobindParam()are indications that the driver is free to ignore.Looking at PDO pg driver’s source code, it appears that, except for
PDO_PARAM_LOBwhich is treated specially, all types are quoted as strings (that is, between quotes and passed to libpq’sPQescapeStringConnfunction)You should also be aware of the
PDO::ATTR_EMULATE_PREPARESattribute that controls what method is used under the hood. Whenfalse,PQprepare()is used with real out-of-query parameters. Iftrue, parameter values are injected into the SQL passed to the non-parametrizedPQexec().Technically, this is quite different, so you may see differing behaviors in corner cases or error cases depending on this attribute.