开发者

How to display results out of a loop (Perl cgi)

开发者 https://www.devze.com 2023-03-16 16:24 出处:网络
I have a question! I have built a cgi file which is doing the following: a loop which querys a database

I have a question! I have built a cgi file which is doing the following:

  • a loop which querys a database
  • while rows are found, build an image and print it

Everything works fine. But now my Problem: if I find too many entries, I don't want to display them. For example: if my searchresult finds more then 50 rows, don't display them!

The pseudo code looks like this:

*while row is found*    
{

 *increase counter of found rows*

 *build and print image*

}

If I find more than 30 entries开发者_运维知识库, the website will load awfully long (displaying all the images) and you have to scroll too much. Sometimes I find more then 600 entries and I don't want to display them at all! So I have to count them first and then make a decision if I want to see them or not.

But how can I display the rows AFTER I counted them? Because I can only print the rows within the while loop.


Either use paging:

How can I do paging and sorting in a Perl CGI program?

Or use a fancy AJAX table to request n results, and have buttons for paging back and fourth between 'pages'


The most efficient way to do this would be to add a LIMIT clause to your SQL query. If you say, for example,

SELECT foo, bar, baz FROM my_table WHERE foo = 1 LIMIT 25;

then the query will never return more than 25 rows. While you could also put a counter into your Perl loop which aborts the loop after the 25th row, that would make the database do the extra work of returning rows that just get thrown away in the end; using LIMIT avoids that waste.


Instead of printing inside your while loop, store your html to a buffer variable, and print it after the loop.

If you have something like this:

while .... {
   print $html
}

Change it to:

$LIMIT = 50;
while ... {
   $buf .= $html;
   $count ++;
   last if ($count > $LIMIT;
}
print $buf if ($count <= $LIMIT);


If you just want to count the rows and exit the loop when you've done 50, you could use something like:

my $count = 0;
while(*row is found* && $count++ < 50)
{
    *stuff*
}

But using SQL LIMIT or the like is better if it works in your case.

0

精彩评论

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