What exactly does the Pdostatement::bindColumn() method do?

Asked

Viewed 124 times

1

This method is for database manipulation. I’m not understanding exactly what it does in the / variable column.

1 answer

2


Serves to assign the value of a column of your Select to a variable.

Note that in the documentation there is a very detailed explanation of this, but to understand you must be familiar with the "passages by reference".

Behold:

 $sql = 'SELECT nome, idade, cpf FROM fruit';
  try {
    $stmt = $dbh->prepare($sql);
    $stmt->execute();

    // Atribuição pela posição da coluna
    $stmt->bindColumn(1, $nome);
    $stmt->bindColumn(2, $idade);

    // atribuição pelo nome da coluna

    $stmt->bindColumn('cpf', $cpf);

    while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
      $data = $nome . "\t" . $idade . "\t" . $cpf . "\n";
      print $data;
    }
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }

All variables passed to the second bindColumn parameter have the value of the column specified above.

In case, when we do bindColumn(1, $nome), the variable $nome is created and passes to point internally to the value of that column, each time the while is rotated.

Note that on the third call of bindColumn in the example, use the name of the column where you want to "tie" (reference or pointer) the value for a variable.

Note that the second argument of bindColumn is a reference, so it has the values assigned according to the call of fetch.

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

To better understand, the functions that possess this sign of & in argument, requires a variable, so that additional values can be returned, since the return is returned something different.

For example is the function fsockopen, that returns a resource. On it, you can pass two parameters by reference to know which is the error or the error code.

 resource fsockopen($host, $port, &$err_no, &$err_str);

That is to say:

 $handle = fsockopen($host, 80, $err_no, $err_str);

 if ($handle === false) {
      throw new Exception($err_str);
 }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.