开发者

MySQL displaying 1 result within while loop...however theirs actually 2 results?

I recently combined 2 queries into 1 (to optimize performance)...1 query for checking the count, and the other for the results, the count is to ensure their is actual results their before proceeding with the loop.

Heres the PHP code:

<?php

    $query = 'SELECT id, title, COUNT(id) FROM submissions ORDER BY sub_time DESC LIMIT 50';

    $result = mysql_query($query);

    $count = mysql_result($result, 0, 2);

    mysql_data_seek($result, 0); //mysql_result resets the internal pointer...

    if ($count > 0) {
        $i = 0;
        while ($output = mysql_fetch_assoc($result)) {
            ++$i;

            //etc..

        }
    }


?>

The problem is it now returns 1 result? - when theirs actually 2 results inside (as I've checked via PHPMyAdmin aswell as running the following code - see below), I've narrowed down the problem, its because the COUNT(id) has been combined with the intial results query; that its behaving like this.

Because if I do the following:

<?php

    $query = 'SELECT id, title FROM submissions ORDER BY sub_time DESC LIMIT 50';

    $result = mysql_query($query);

        $i = 0;
        while ($output = mysql_fetch_assoc($result)) {
            ++$i;

            //etc..

        }

?>

It returns 2 results...

开发者_如何学CSo my question is how do i resolve this but achieve what I'm after?


I would recommend that you remove the COUNT(id) and use the mysql_num_rows() function to check how many rows were returned before trying to loop through them.

Your code could then look like this:

<?php

$query = 'SELECT id, title FROM submissions ORDER BY sub_time DESC LIMIT 50';

$result = mysql_query($query);

$count = mysql_num_rows($result);

if ($count > 0) {
    $i = 0;
    while ($output = mysql_fetch_assoc($result)) {
        ++$i;

        //etc..

    }
}


COUNT is an aggregate function that typically is used with the GROUP BY clause. I don't believe it is meaningful in the query as you used it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜