使用 PDO 获取单行、单列
我有一个 mysql 查询,其目标是单行中的单列
"SELECT some_col_name FROM table_name WHERE user=:user"
在执行语句 $stmt->execute();
后,如何将此单个单元格直接放入变量中而无需循环?换句话说,如何获得
from $stmt->execute();
to $col_value = 100;
我尝试了下面的2,但都不起作用。该列在原始表中是数字4,但我假设因为在我的选择语句中我只选择它,所以当我选择它时它应该是1指定 fetchColumn 的参数。
$col_value = $stmt->fetchColumn();
$col_value = $stmt->fetchColumn(0);
正如你所看到的,我试图用尽可能少的行来完成它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你可以使用这个:
You could use this:
我不知道为什么这么多人搞砸了:
确保您在查询中选择特定的
列
而不是*
,否则您将需要指定该列fetchColumn()
中的订单号,例如:$stmt->fetchColumn(2);
这通常不是一个好主意,因为数据库中的列可能会被重新组织由某人...这仅适用于
唯一的“wheres”
;fetchColumn()
不会返回数组。I'm not sure why so many people mess this up:
Make sure that you are selecting a specific
column
in the query and not*
or you will need to specify the column order number infetchColumn()
, 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.当您想要获取最后一条插入时,请将 DESC Limit 1 添加到 sql 语句中。
When you want to get the last insert you add the DESC Limit 1 to the sql statement.
你先准备好声明了吗? (在
$stmt->execute()
之前)Have you prepared the statement first? (Before
$stmt->execute()
)您确定它返回任何行吗?
是获取单个值的正确方法,因此您可能没有绑定 :user 参数,或者它只是不返回任何行。
Are you sure it's returning any rows?
is correct way to fetch a single value, so either you probably didn't bind the :user parameter or it simply returned no rows.