PDO预处理

方法:bool PDOStatement::execute ([ array $input_parameters ] )

分为3步: 
1. 使用 prepare() 准备预处理SQL; 
2. 绑定参数或值; 
3. 调用 execute() 执行SQL。

其中后面两步可以合并。

 

预处理

 

执行一条问号占位符的预处理语句(占位符)

示例:

<?php
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();

 bindParam() 只有前两个参数是必选。第三个参数默认是 PDO::PARAM_STR 。

 

执行一条绑定变量的预处理语句(命名参数)

示例:

<?php
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();

测试发现:使用命名参数绑定的时候, bindParam 第一个参数没写冒号,也可以执行的:

$sth->bindParam('calories', $calories, PDO::PARAM_INT);
$sth->bindParam('colour', $colour, PDO::PARAM_STR, 12);

但不建议这样写。

 

使用一个含有插入值的数组执行一条预处理语句(占位符)

示例:

 
<?php
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->execute(array($calories, $colour));

数组里值一定要和SQL里参数顺序一致。

 

使用一个含有插入值的数组执行一条预处理语句(命名参数)

示例:

 
<?php
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->execute(array(
    ':calories' => $calories, 
    ':colour' => $colour
));

推荐使用这种方式。

 

bindParam() 和 bindValue()的区别

 方法 bindParam()  和  bindValue()  非常相似,唯一的区别就是前者使用一个PHP变量绑定参数,而后者使用一个值。

所以使用bindParam是第二个参数只能用变量名,而不能用变量值,而 bindValue() 至可以使用具体值。

示例:

 
<?php
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);//正确
$sth->bindValue(1, $calories, PDO::PARAM_INT);//正确
$sth->bindParam(1, 150, PDO::PARAM_INT);//错误,必须是参数
$sth->bindValue(1, 150, PDO::PARAM_INT);//正确
$sth->execute();

另外在存储过程中, bindParam 可以绑定为 input/output 变量,如下面

 
$sth = $pdo->prepare("call func(:param)");  
$param = "test";  
$sth->bindParam(":param",$param); //正确  
$sth->execute();  

存储过程执行过后的结果可以直接反应到变量上。对于那些内存中的大数据块参数,处于性能的考虑,应优先使用 bindParam() 。

 

拓展阅读

1、PDOStatement::execute http://www.runoob.com/php/pdostatement-execute.html 
2、php pdo中bindParam() 和 bindValue()方法的区别 https://blog.csdn.net/think2me/article/details/7258509 
3、官网介绍pdo的execute这么绑定命名参数,但是不写冒号也行 https://segmentfault.com/q/1010000007480197 
4、Yaf封装MySQL https://blog.csdn.net/doomsday0417/article/details/70810366

原文地址:https://www.cnblogs.com/52fhy/p/3969308.html