PDO:fetchColumn是否移动了返回结果集的指针?
我最近实现了 PDO,并注意到我的查询结果缺少第一行。这可能是因为 fetchColumn() 检索第一行并将指针移动到第二行,以便 while() 循环从第 2 行开始。这是正确的吗?如果是这样,我该如何避免这种情况并改进以下代码块?
$STH = $DBH->prepare("SELECT * FROM users");
$result = $STH->execute();
if (!$result)
{
return false;
}
elseif($STH->fetchColumn()>0)//counterpart of mysql_num_rows()
{
while ($row = $STH->fetch())
{
...
}
}
}
I recently implemented PDO and noticed that my query results lacked the first row. That's probably because fetchColumn() retrieves the first row and moves the pointer to the second row so that the while() loop starts at row 2. Is that correct? If so, how can I avoid that and improve the following code block?
$STH = $DBH->prepare("SELECT * FROM users");
$result = $STH->execute();
if (!$result)
{
return false;
}
elseif($STH->fetchColumn()>0)//counterpart of mysql_num_rows()
{
while ($row = $STH->fetch())
{
...
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。此外,
fetchColumn()
并不等同于mysql_num_rows()
。相反,fetchColumn()
检索当前行的索引列值(默认为索引 0),并按假设前进游标。如果您需要计算查询中返回的行数,我建议您首先使用
fetchColumn()< 发出具有相同条件的
SELECT COUNT(1) ...
查询/code> 返回计数。请参阅本手册页上的示例#2 - http://www.php.net/ Manual/en/pdostatement.rowcount.php
例如
Yes. Also,
fetchColumn()
is not an equivalent formysql_num_rows()
. Instead,fetchColumn()
retrieves the indexed column value (defaulting to index 0) of the current row and as assumed, advances the cursor.If you need a count of the number of rows returned in your query, I suggest you first issue a
SELECT COUNT(1) ...
query with the same conditions, usingfetchColumn()
to return the count.See example #2 on this manual page - http://www.php.net/manual/en/pdostatement.rowcount.php
For example
经过谷歌搜索后,我想出了这个解决方案:
After googling around I came up with this solution: