Search code examples
phpmysqlpdo

PDO::PARAM_INT is important in bindParam?


Add PDO::PARAM_INT or PDO::PARAM_STR have any meaning in Mysql query?

$sql  = 'SELECT TagId FROM tagthread WHERE ThreadId = :ThreadId';

$stmt = $this->db->prepare($sql);
$stmt->bindParam(':ThreadId', $threadid, PDO::PARAM_INT);

$stmt->execute();

Solution

  • Yes, use it.

    I did a few tests (with PDO::ATTR_EMULATE_PREPARES false) and I found out that the quotes around the values will be different.

    When you bind an integer value with PARAM_INT there will be no quotes in the query (A string value with PARAM_INT has quotes). If you bind an integer value with PDO::PARAM_STR there will be quotes and mysql has to cast to integer.

    Examples:

    $stmt->bindParam(':ThreadId', $threadid, PDO::PARAM_INT);
    $threadid = 123;
    // SELECT TagId FROM tagthread WHERE ThreadId = 123
    $threadid = '123test';
    // SELECT TagId FROM tagthread WHERE ThreadId = '123test'
    // mysql will cast 123test to 123
    

    EDIT:

    I further tested and read on that topic. Conclusion: Implicit casting is dangerous and can lead to unexpected results. Read more on that here. Another disadvantage to always use PDO::PARAM_STR is the performance. Read more on performance Disadvantages of quoting integers in a Mysql query?

    So if your column is of type [TINY|SMALL|MEDIUM|BIG]INT than use PARAM_INT. And in case it is a LIMIT clause than cast to integer if the variable type in PHP is not integer.