bindParam()、bindValue()和execute(array())有什么区别和优势

What is the differences and advantages between bindParam(), bindValue() and execute(array())

<?php

    $db = new PDO($dsn,$username,$password);
    $uname='avi';
    $age=19;
    $stmt = $db->prepare('INSERT INTO table(uname,age) VALUES(:uname,:age)');
    $stmt->execute(array(':uname'=>$uname,':age'=>$age));

    $stmt = $db->prepare('INSERT INTO table(uname,age) VALUES(?,?)');
    $stmt->execute(array($uname,$age));

    $stmt = $db->prepare('INSERT INTO table(uname,age) VALUES(:uname,:age)');
    $stmt->bindValue(':uname',$uname); //can be $uname or just 'avi'
    $stmt->binParam(':age',$uname); //cannot be 'avi' or value only
    $stmt->execute();

?>

我们什么时候应该使用bindParam()?以前的所有方法似乎都更简单,需要的代码行更少。

与其他方法(bindValue()execute())相比,使用 bindParam() 有什么好处?

bindParam() binds the parameter by reference, so it will be evaluated at $stmt->execute(), which is unlike bindValue() 在调用函数本身时进行计算。

举个例子:

绑定参数:

<?php

    try {

        $dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $dbh->prepare("SELECT * FROM test WHERE number = ?");
        $stmt->bindParam(1, $xy, PDO::PARAM_INT);
        $xy = 123;  //See here variable is defined after it has been bind
        $stmt->execute();

        print_r($stmt->fetchAll());

    } catch(PDOException $e) {
        echo $e->getMessage();
    }

?>

效果很好!

绑定值:

<?php

    try {

        $dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $dbh->prepare("SELECT * FROM test WHERE number = ?");
        $stmt->bindValue(1, $xy, PDO::PARAM_INT);
        $xy = 123;  //See here variable is defined after it has been bind
        $stmt->execute();

        print_r($stmt->fetchAll());

    } catch(PDOException $e) {
        echo $e->getMessage();
    }

?>

输出:

Notice: Undefined variable: xy

还有一些其他差异:

  • bindParam() 也有参数长度,如果您调用 IN&OUT 过程将输出存储回变量(这还需要附加 PDO::PARAM_INPUT_OUTPUT 或类型参数的声明)
  • 使用 bindParam() & bindValue() 你可以指定值的类型,这在 execute() 中是做不到的,那里的一切都只是一个字符串 (PDO:: PARAM_STR)

bindParam 优于 bindValue 的好处是您可以在决定将什么放入其中之前绑定变量。为什么你真的需要这样做,我不知道,但你可能会。

绑定值

$x = function_call_to_determine_value();
$stmt->bindValue(':x',$x);
$stmt->execute();

绑定参数

$stmt->bindParam(':x',$x);
$x = function_call_to_determine_value();
$stmt->execute();