PDOStatement::bindColumn

PHP PDO 参考手册PHP PDO Reference Manual

PDOStatement::bindColumn — Bind a column to a PHP variable (PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)


Description

Syntax

bool PDOStatement::bindColumn ( mixed $column , mixed &$param [, int $type [, int $maxlen [, mixed $driverdata ]]] )

Binds a specific variable to a given column in the result set of a query. Each call to PDOStatement::fetch() or PDOStatement::fetchAll() will update all variables bound to columns.

Note:Not all column information is always available before the statement is executed. Portable applications should call this function (method) after PDOStatement::execute().
However, when using the PgSQL driver, to be able to bind a LOB column as a stream, the application must call this method before calling PDOStatement::execute(), otherwise the large object OID is returned as an integer.


Parameters

column
The column number (indexed from 1) or column name in the result set. If using a column name, note that the name should match the case of the column name returned by the driver.

param
The name of the PHP variable to bind to the column

type
The data type of the parameter, specified by the PDO::PARAM_* constants.

maxlen
Pre-allocation hint.

driverdata
Driver-specific optional parameter.


Return Values

Returns TRUE on success, or FALSE on failure.


Examples

Bind result set output to PHP variables

Binding columns in the result set to PHP variables is an effective way to make the data contained in each row immediately available to the application. The following example demonstrates how PDO binds and retrieves columns with various options and defaults.

<?php
function readData($dbh) {
  $sql = 'SELECT name, colour, calories FROM fruit';
  try {
    $stmt = $dbh->prepare($sql);
    $stmt->execute();

    /*  通过列号绑定  */
    $stmt->bindColumn(1, $name);
    $stmt->bindColumn(2, $colour);
    
    /*  通过列名绑定  */
    $stmt->bindColumn('calories', $cals);

    while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
      $data = $name . "\t" . $colour . "\t" . $cals . "\n";
      print $data;
    }
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}
readData($dbh);
?>

The above routine will output:

apple   red     150
banana  yellow  175
kiwi    green   75
orange  orange  150
mango   red     200
strawberry      red     25

PHP PDO 参考手册PHP PDO Reference Manual

Other extensions