Question

I'm passing three parameter to URL: &p1=eventID, &p2=firstItem, &p3=numberOfItems. first parameter is a column of table. second parameter is the first item that I'm looking for. Third parameter says pick how many items after firstItem.

for example in first query user send &p1=1, &p2=0, &p3=20. Therefore, I need first 20 items of list. Next time if user sends &p1=1, &p2=21, &p3=20, then I should pass second 20 items (from item 21 to item 41).

PHP file is able to get parameters. currently, I'm using following string to query into database:

public function getPlaceList($eventId, $firstItem, $numberOfItems) {
        $records = array();
        $query = "select * from {$this->TB_ACT_PLACES} where eventid={$eventId}";

        ...
}

Result is a long list of items. If I add LIMIT 20 at the end of string, then since I'm not using Token then result always is same.

how to change the query in a way that meets my requirement? any suggestion would be appreciated. Thanks

=> update: I can get the whole list of items and then select from my first item to last item via for(;;) loop. But I want to know is it possible to do similar thing via sql? I guess this way is more efficient way.

Was it helpful?

Solution 3

I found my answer here: stackoverflow.com/a/8242764/513413

For other's reference, I changed my query based on what Joel and above link said:

$query = "select places.title, places.summary, places.description, places.year, places.date from places where places.eventid = $eventId order by places.date limit $numberOfItems offset $firstItem"; 

OTHER TIPS

I would construct the final query to be like this:

SELECT <column list> /* never use "select *" in production! */
FROM Table
WHERE p1ColumnName >= p2FirstItem
ORDER BY p1ColumnName
LIMIT p3NumberOfItems

The ORDER BY is important; according to my reading of the documentation, PostGreSql won't guarantee which rows you get without it. I know Sql Server works much the same way.

Beyond this, I'm not sure how to build this query safely. You'll need to be very careful that your method for constructing that sql statement does not leave you vulnerable to sql injection attacks. At first glance, it looks like I could very easily put a malicious value into your column name url parameter.

If you are using mysql, then use the LIMIT keyword.

SELECT *
 FROM Table
 LIMIT $firstItem, $numberOfItems

See the documentation here (search for LIMIT in the page).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top