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.
PDO::FETCH_BOTH (default) Returns an array indexed by both column name and 0-indexed column number as returned in your result set.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With