duanli9569 2011-09-06 22:06 采纳率: 100%
浏览 119
已采纳

如何在PDOStatement :: bindValue()中定义变量类型?

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

PDOStatement::bindValue ( $parameter , $value [, $data_type = PDO::PARAM_STR ] )

I'm wondering, what's the purpose of specifying the data type, whereas when leaved as default (PARAM_STR) eventually the database will anyway cast the value to the proper type before using it?

For example, if you have these queries over an INTEGER field:

INSERT INTO table (integerField) VALUES (?) ;
SELECT * FROM table WHERE integerField = ?  ;

And you bind an integer in PHP, PDO will by default bind it as a string, which is equivalent as:

INSERT INTO table (integerField) VALUES ("1") ;
SELECT * FROM table WHERE integerField = "1"  ;

That will work flawlessly, because the SQL database (at least MySQL, I'm not really aware of how that would work on other RDBMS) knows how to convert the string back to an integer before using it.

What are the use cases where it would make a difference to bound typed parameters vs strings?

  • 写回答

3条回答 默认 最新

  • dtc99987 2011-09-10 17:20
    关注

    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..."
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab