Home > PDO, PDOStatement->fetchColumn > PDOStatement->fetchColumn

PDOStatement->fetchColumn


Here is the database I used: http://download.vive.net/Northwind.zip

I think of PDOStatement->fetchColumn as a handy function to fetch data from a field
as a string. Or, if you think as a database as a spreadsheet, we’d be fetching
a single cell as a string.

<?php
$dbh = new PDO('sqlite:northwind.sqlite');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$sql = $dbh->prepare('SELECT CategoryName FROM categories where CategoryID = 1');
$sql->execute();
$result = $sql->fetchColumn();
echo $result; //Beverage
?>

As you can see the columns are zero indexed.


<?php
$dbh = new PDO('sqlite:northwind.sqlite');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$sql = $dbh->prepare('SELECT CategoryName, Description FROM categories where CategoryID = 1');
$sql->execute();
echo $sql->fetchColumn();
$sql->execute();
echo $result = $sql->fetchColumn(1);

//BeveragesSoft drinks, coffees, teas, beers, and ales

So why is it called fetchColumn? THe best guess I’ve heard is that a database can fetch an entire row at a time, but only a single column. If you think about it, an entire row but a single column is the exact same thing as a single cell, or field.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: