Tuesday, July 03, 2012

Why use LIKE instate of using loop in PHP ?


We know LIMIT counts from the first row of the results. However, by including two numbers after the
LIMIT keyword, separated by a comma, you can specify both the row from which to start returning
results, as well as the number of results to return:

mysql> SELECT id, username FROM members LIMIT 1, 2;

| id | username |
-------------------
 2    ron
 3    anjan

Notice that the start row counts from zero, so 1 is actually the second row (ron).

You might be wondering what the point of LIMIT is, because you can always just loop through the result set in PHP to extract only the rows you’re interested in. The main reason to use LIMIT is that it reduces the amount of data that has to flow between MySQL and your PHP script.

Imagine that you want to retrieve the first 100 rows of a million-row table of users. If you use LIMIT
100, only 100 rows are sent to your PHP script. However, if you don’t use a LIMIT clause (and your
query also contains no WHERE clause), all 1,000,000 rows of data will be sent to your PHP script, where they will need to be stored inside a PDOStatement object until you loop through them to extract the first 100. Storing the details of a million users in your script will quickly bring the script to a halt, due to the large amount of memory required to do so.
LIMIT is particularly useful when you’re building a paged search function in your PHP application. For example, if the user requests the second page of search results, and you display 10 results per page, you can use SELECT ... LIMIT 10, 10 to retrieve the second page of results.

No comments:

Post a Comment