为什么我的 count() 子句会破坏 while 语句?

发布于 2024-10-04 18:18:40 字数 2374 浏览 4 评论 0原文

我的 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; ?>&nbsp;<?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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你与清晨阳光 2024-10-11 18:18:40

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.

﹂绝世的画 2024-10-11 18:18:40

如果结果总数超过
5、提供查看其他地方所有内容的链接

要确定没有 LIMIT 子句时返回的行数,请使用 SQL_CALC_FOUND_ROWS

SELECT SQL_CALC_FOUND_ROWS ID, fname, lname FROM tablename WHERE fname LIKE ? or lname LIKE ? ORDER BY ID LIMIT 5

然后,您对 SELECT FOUND_ROWS() 的调用将返回没有限制的数字。注意:SELECT SQL_CALC_FOUND_ROWSSELECT FOUND_ROWS() 语句之间不应发生其他 SQL 调用,否则值将不正确。

if the total number of results exceed
5, provide link to view all elsewhere

To determine the number of rows that would have been returned had there been no LIMIT clause, use SQL_CALC_FOUND_ROWS

SELECT SQL_CALC_FOUND_ROWS ID, fname, lname FROM tablename WHERE fname LIKE ? or lname LIKE ? ORDER BY ID LIMIT 5

Then, your call to SELECT FOUND_ROWS() will return the number had there been no limit. Note: No other SQL calls should occur between the SELECT SQL_CALC_FOUND_ROWS and the SELECT FOUND_ROWS() statement or the value will not be correct.

蛮可爱 2024-10-11 18:18:40

这与 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文