当前位置:主页 > 软件编程 > PHP代码 >

PHP PDOStatement::bindParam讲解

时间:2021-07-22 07:48:09 | 栏目:PHP代码 | 点击:

PDOStatement::bindParam

PDOStatement::bindParam ― 绑定一个参数到指定的变量名(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

说明

语法

bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )

绑定一个PHP变量到用作预处理的SQL语句中的对应命名占位符或问号占位符。 不同于PDOStatement::bindValue() ,此变量作为引用被绑定,并只在PDOStatement::execute()被调用的时候才取其值。

大多数参数是输入参数,即,参数以只读的方式用来建立查询。一些驱动支持调用存储过程并作为输出参数返回数据,一些支持作为输入/输出参数,既发送数据又接收更新后的数据。

参数

parameter

variable

data_type

length

driverdata

driver_options

返回值

成功时返回 TRUE,或者在失败时返回 FALSE。

实例

执行一条使用命名占位符的预处理语句

<?php
/* 通过绑定的 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();
?>

执行一条使用问号占位符的预处理语句

<?php
/* 通过绑定的 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();
?>

使用 INOUT 参数调用一个存储过程

<?php
/* 使用 INOUT 参数调用一个存储过程 */
$colour = 'red';
$sth = $dbh->prepare('CALL puree_fruit(?)');
$sth->bindParam(1, $colour, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 12);
$sth->execute();
print("After pureeing fruit, the colour is: $colour");
?>

总结

您可能感兴趣的文章:

相关文章