为什么我的 count() 子句会破坏 while 语句?
我的 SQL 调用遇到问题。最终,我从搜索框运行 AJAX 调用并将结果返回到屏幕。我将显示的结果限制为 5 个,但如果结果总数超过 5 个,请提供链接以在其他地方查看所有结果。我认为通过简单地添加一个 COUNT()
子句就可以解决这个问题,虽然 COUNT()
确实正确返回匹配的完整数量,但它杀死了我的 < code>while 语句循环时只返回第一个结果。当我删除 count()
时,一切正常。
代码
<?php
if(isset($_POST['word']) && $_POST['word'] != "")
{
$q=$_POST['word'];
try {
$db = new PDO('mysql:host=localhost;dbname=DB', 'USER', 'PW');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$stmt = $db->prepare("SELECT COUNT(ID) as counter, ID, fname, lname FROM tablename WHERE fname LIKE ? or lname LIKE ? ORDER BY ID LIMIT 5");
$stmt->execute(array('%'.$q.'%', '%'.$q.'%'));
$foundrows = $db->query("SELECT FOUND_ROWS()")->fetchColumn();
$db->commit();
}
catch (PDOException $e)
{
echo "There was a system DB error. <br>".$e->getMessage();
}
if(isset($foundrows) && $foundrows == 0) {
echo "<div class='display_box' align='left'>
No matching results found</div>";
} else {
while($row = $stmt->fetch()) {
$counter = $row['counter'];
$id = $row['ID'];
$fname = $row['fname'];
$lname = $row['lname'];
?>
<a href="#" style="text-decoration:none; color:#000;">
<div class="display_box" align="left">
<?php echo $fname; ?> <?php echo $lname; ?><br/>
</div></a>
<?php
}
if(isset($counter) && $counter > 5) {
?>
<a href="#" style="text-decoration:none; color:#000;">
<div class="display_box" align="left">
<?php echo (5-$counter)." additional matches found."; ?>
</div></a>
<?php
}
}
}
?>
I am having an issue with a SQL call I have. Ultimately, I am running an AJAX call from a search box and returning the results to screen. I limit the results to 5 displayed but if the total number of results exceed 5, provide link to view all elsewhere. I thought by simply adding a COUNT()
clause in this would take care of the issue and while COUNT()
does return the full number of matches correctly, it kills my while
statement when looping through and only returns the first result. When I remove count()
, everything works.
CODE
<?php
if(isset($_POST['word']) && $_POST['word'] != "")
{
$q=$_POST['word'];
try {
$db = new PDO('mysql:host=localhost;dbname=DB', 'USER', 'PW');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$stmt = $db->prepare("SELECT COUNT(ID) as counter, ID, fname, lname FROM tablename WHERE fname LIKE ? or lname LIKE ? ORDER BY ID LIMIT 5");
$stmt->execute(array('%'.$q.'%', '%'.$q.'%'));
$foundrows = $db->query("SELECT FOUND_ROWS()")->fetchColumn();
$db->commit();
}
catch (PDOException $e)
{
echo "There was a system DB error. <br>".$e->getMessage();
}
if(isset($foundrows) && $foundrows == 0) {
echo "<div class='display_box' align='left'>
No matching results found</div>";
} else {
while($row = $stmt->fetch()) {
$counter = $row['counter'];
$id = $row['ID'];
$fname = $row['fname'];
$lname = $row['lname'];
?>
<a href="#" style="text-decoration:none; color:#000;">
<div class="display_box" align="left">
<?php echo $fname; ?> <?php echo $lname; ?><br/>
</div></a>
<?php
}
if(isset($counter) && $counter > 5) {
?>
<a href="#" style="text-decoration:none; color:#000;">
<div class="display_box" align="left">
<?php echo (5-$counter)." additional matches found."; ?>
</div></a>
<?php
}
}
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
COUNT()
是对表的聚合操作,仅返回一行,这就是为什么在包含查询时您没有获得预期的 5 个结果。获得所需结果的一种方法是在查询中使用 SUBSELECT 子句:
SELECT (SELECT COUNT(ID) FROM tablename) as counter, ID, fname, lname FROM tablename WHERE fname喜欢 ?或我的名字像? ORDER BY ID LIMIT 5
这将返回您期望的 5 个结果,并将表中行的完整计数作为每行中的一列。
COUNT()
is an aggregate operation on the table that returns just one row, which is why you're not getting 5 results as you expect from your query when including it.One way you can get what you want is by using a
SUBSELECT
clause in your query:SELECT (SELECT COUNT(ID) FROM tablename) as counter, ID, fname, lname FROM tablename WHERE fname LIKE ? or lname LIKE ? ORDER BY ID LIMIT 5
This will return the 5 results you expect, with a full count of the rows in the table as a column in each row.
要确定没有 LIMIT 子句时返回的行数,请使用 SQL_CALC_FOUND_ROWS
然后,您对
SELECT FOUND_ROWS()
的调用将返回没有限制的数字。注意:SELECT SQL_CALC_FOUND_ROWS
和SELECT FOUND_ROWS()
语句之间不应发生其他 SQL 调用,否则值将不正确。To determine the number of rows that would have been returned had there been no LIMIT clause, use SQL_CALC_FOUND_ROWS
Then, your call to
SELECT FOUND_ROWS()
will return the number had there been no limit. Note: No other SQL calls should occur between theSELECT SQL_CALC_FOUND_ROWS
and theSELECT FOUND_ROWS()
statement or the value will not be correct.这与 PDO 或 PHP 无关。如果您指定聚合函数(例如 COUNT()、MAX()...),它需要对行进行分组,因为您无法计算单行(当然)。如果您不指定GROUP BY,它将折叠整个结果集。
That has nothing to do with PDO or PHP. If you specify an aggregate function (like COUNT(), MAX(), ...) it needs to group the rows, because you can not count a single row (of course). If you do not specify GROUP BY it will collapse the whole result set.