Fetching single row, single column with PDO Fetching single row, single column with PDO database database

Fetching single row, single column with PDO


Are you sure it's returning any rows?

$stmt->fetchColumn()

is correct way to fetch a single value, so either you probably didn't bind the :user parameter or it simply returned no rows.


$sql='SELECT some_col_name FROM table_name WHERE user=?';$sth=$pdo_dbh->prepare($sql);$data=array($user);$sth->execute($data);$result=$sth->fetchColumn();


I'm not sure why so many people mess this up:

$stmt = $dbh->prepare("SELECT `column` FROM `table` WHERE `where`=:where"); $stmt->bindValue(':where', $MyWhere);$stmt->execute();$SingleVar = $stmt->fetchColumn();

Make sure that you are selecting a specific column in the query and not * or you will need to specify the column order number in fetchColumn(), example: $stmt->fetchColumn(2); That usually isn't a good idea because the columns in the database may be reorganized by, someone...

This will only work properly with unique 'wheres'; fetchColumn() will not return an array.