← Back to Chapters

PHP PDO – bindColumn Method

? PHP PDO – bindColumn Method

? Quick Overview

The bindColumn() method in PHP PDO binds individual columns from a database result set directly to PHP variables. Each fetch operation automatically updates those variables, making it efficient for processing large datasets.

? Key Concepts

  • bindColumn() maps a column to a PHP variable.
  • Binding can be done using column index or column name.
  • Works with PDO::FETCH_BOUND fetch mode.
  • Reduces memory overhead for large result sets.

? Syntax / Theory

After preparing and executing a statement, columns are bound using bindColumn(). When rows are fetched using PDO::FETCH_BOUND, the bound variables receive updated values automatically.

? Code Example

? View Code Example
// Connecting to database and binding result columns
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare("SELECT id, name, email FROM users");
$stmt->execute();

$stmt->bindColumn(1, $id);
$stmt->bindColumn(2, $name);
$stmt->bindColumn(3, $email);

while ($stmt->fetch(PDO::FETCH_BOUND)) {
echo "ID: $id - Name: $name - Email: $email<br>";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>

? Live Output / Explanation

Each database row updates the variables $id, $name, and $email. The loop prints user details directly without accessing an array.

? Interactive Concept

Think of bindColumn() as a live wire: each fetch sends new data through the same variable. This is especially useful when streaming records one-by-one.

? Use Cases

  • Processing large user tables efficiently
  • Streaming reports or exports
  • Reducing memory usage in long loops
  • Mapping database columns directly to variables

✅ Tips & Best Practices

  • Use column names instead of indexes for clarity.
  • Always execute the statement before binding columns.
  • Combine with bindParam() when needed.

? Try It Yourself

  • Bind columns using column names instead of numbers.
  • Display only the name column.
  • Add and bind an extra column like created_at.