• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • PDOStatement::bindColumn()

    (PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

    绑定一列到一个 PHP 变量

    说明

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

    安排一个特定的变量绑定到一个查询结果集中给定的列。每次调用PDOStatement::fetch()或PDOStatement::fetchAll()都将更新所有绑定到列的变量。

    Note:

    在语句执行前 PDO 有关列的信息并非总是可用,可移植的应用应在PDOStatement::execute()之后调用此函数(方法)。

    但是,当使用PgSQL 驱动时,要想能绑定一个 LOB 列作为流,应用程序必须在调用PDOStatement::execute()之前调用此方法,否则大对象 OID 作为一个整数返回。

    参数

    $column

    结果集中的列号(从1开始索引)或列名。如果使用列名,注意名称应该与由驱动返回的列名大小写保持一致。

    $param

    将绑定到列的 PHP 变量名称

    $type

    通过 PDO::PARAM_*常量指定的参数的数据类型。

    $maxlen

    预分配提示。

    $driverdata

    驱动的可选参数。

    返回值

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

    范例

    把结果集输出绑定到 PHP 变量

    绑定结果集中的列到PHP变量是一种使每行包含的数据在应用程序中立即可用的有效方法。下面的例子演示了 PDO 怎样用多种选项和缺省值绑定和检索列。

    <?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);
    ?>
    

    以上例程会输出:

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

    参见

    • PDOStatement::execute() 执行一条预处理语句
    • PDOStatement::fetch() 从结果集中获取下一行
    • PDOStatement::fetchAll() 返回一个包含结果集中所有行的数组
    • PDOStatement::fetchColumn() 从结果集中的下一行返回单独的一列。
    Hello,
    it is important to keep in mind that in any SQL query, the names of the columns should be surrounded by reverse quotes (`).
    <?php 
    $sql = "SELECT `col1`, `col2` FROM table";
    ?>
    To prevent any confusion with SQL reserved words. For example, I have had a column called 'key' and it has been a hard time to fix the bug. Since I have used `key`, it's fine.