How define the variable type in PDOStatement::bindValue()?

后端 未结 3 715
甜味超标
甜味超标 2021-02-08 19:36

The PDOStatement::bindValue() method offers a way to specify the type of the variable bound:

PDOStatement::bindValue ( $parameter , $value [, $da

3条回答
  •  眼角桃花
    2021-02-08 20:22

    I'm no PDO-expert, but I can think of a few scenarioes where the data_type parameter is both useful and even needed.

    Output parameters

    When you define output or input/output parameters, you must provide both type and length of the expected output parameter.

    Ref: http://www.php.net/manual/en/pdo.prepared-statements.php

    Example #4

    $stmt = $dbh->prepare("CALL sp_returns_string(?)");
    $stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000); 
    

    Example #5

    $stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
    $value = 'hello';
    $stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); 
    

    DBMs without implicit casting

    Explained in another answer to this question...

    When parameter is not bound to castable data

    Even databases with casting abilities will not always be able to cast you variable correctly.

    Ref: Reasons to strongly type parameters in PDO?

    $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..."
    

提交回复
热议问题