PDO::PARAM_INT is important in bindParam?

前端 未结 3 1536
天涯浪人
天涯浪人 2020-12-15 04:44

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

$sql  = \'SELECT TagId FROM tagthread WHERE ThreadId = :Threa         


        
3条回答
  •  误落风尘
    2020-12-15 05:24

    I cannot tell for all the drivers supported by PDO, but for mysql it's ok not to use PDO::PARAM_INT most of time.

    Therefore, it makes no sense to bloat your code with numerous bindParam calls. As a rule, just send your variables directly into execute():

    $sql  = 'SELECT TagId FROM tagthread WHERE ThreadId = ?';
    $stmt = $this->db->prepare($sql);
    $stmt->execute([$threadid]);
    

    Here your $threadid variable will be silently bound as a string, but it will make not a single problem for mysql to compare it with integer value stored in database. In reality, everyone does it this way and never has any problem.

    The problem with string type bindnig in LIMIT clause can be easily solved by switfhing the emulation mode OFF.

    Note that PDO::PARAM_INT doesn't cast your value. Means if you're trying to bind a string type value using this mode, it will be bound as a string nevertheless, even if you explicitly set type to PDO::PARAM_INT. This mode will be actually applied only for integer values.

    There are few edge cases where you may want to bind an integer explicitly though:

    • peculiar column types, like BIGINT or BOOLEAN that require an operand of exact type to be bound (note that in order to bind a BIGINT value with PDO::PARAM_INT you need a mysqlnd-based installation).
    • some DBAs claim that complex queries with non-trivial query plan can be affected by a wrong operand type. though noone provided a verifiable example yet

    All other issues are common for the loose typing and neither mysql nor PDO binding has any special effect in them.

    Also, to avoid possible problems you should choose right column types for your data. Say, for big integers you should use BIGINT, while for any price-like data it have to be DECIMAL. And there will be not a single issue with comparison.

提交回复
热议问题