Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching single row, single column with PDO

I have a mysql query that targets a single column in a single row

"SELECT some_col_name FROM table_name WHERE user=:user" 

After I execute the statement $stmt->execute(); how do I get this single cell directly placed into a variable with no loops? In other words how to get

from $stmt->execute();  to $col_value = 100; 

I tried the 2 below, but neither worked.. The column is number 4 in the original table, but I'm assuming since in my select statement I'm selecting it only, it should be 1 when I specify the parameter for fetchColumn.

$col_value = $stmt->fetchColumn(); $col_value = $stmt->fetchColumn(0); 

As you can see, I'm trying to do it in as few lines as possible.

like image 967
Chris Avatar asked Nov 03 '09 11:11

Chris


People also ask

Which one is default mode of fetching data in PDO?

PDO::FETCH_BOTH (default) Returns an array indexed by both column name and 0-indexed column number as returned in your result set.

How fetch data from database in PHP and display PDO?

Fetch data from a result set by calling one of the following fetch methods: To return a single row from a result set as an array or object, call the PDOStatement::fetch method. To return all of the rows from the result set as an array of arrays or objects, call the PDOStatement::fetchAll method.

What is PDO :: Fetch_assoc?

PDO::FETCH_ASSOC. Specifies an array indexed by column name. PDO::FETCH_BOTH. Specifies an array indexed by column name and 0-based order. This is the default.


2 Answers

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.

like image 87
reko_t Avatar answered Oct 05 '22 18:10

reko_t


$sql='SELECT some_col_name FROM table_name WHERE user=?';  $sth=$pdo_dbh->prepare($sql); $data=array($user);  $sth->execute($data);  $result=$sth->fetchColumn(); 
like image 44
JAL Avatar answered Oct 05 '22 19:10

JAL