I have an article system which is used by several users. Articles have their own permissions which gets checked against the viewer’s ID for each article that runs through my while loop. I limit the articles by incrementing $printcount if the user is allowed to view the article, and the loop terminates when it reaches $limit. I also have sorting options to sort by name, date inserted, date modified and submitted by.
How would I go about utilizing next/previous page buttons without using MySQL limit features? Here is a short version of my code (may not be 100% functional, but should bring the point across)
<?php
$sort=$_GET['sort']; // date_added
$direction=$_GET['dir']; // ASC
$limit=$_GET['limit']; // 25
$query="SELECT * FROM `article` ORDER BY '$sort' '$direction'";
$result=mysql_query($query);
if(mysql_num_rows($result)==NULL) {
echo '<tr><td colspan="4">NO RECORDS FOUND</td></tr>';
}
$printcount=0;
while(($row=mysql_fetch_assoc($result))&&($printcount<$limit+1)) {
//if user is owner of article $readable=true;
//load permissions from permission column (comma separated integers) into array, if user's group ID is in that array $readable=true;
//if article "global_read" flag=1, $readable=true;
//if $printcount<$limit, and $readable echo the table row with data
//if $readable, $printcount++;
}
?>
If I were only sorting by ID ASC, I could easily store the ID as a last_id, and on next page the query would have an additional: WHERE , but since there are different sort options and direction options this seems to be much more complicated.`id` > $last_ID
I’m assuming you’re asking this question because your permission model is handled in the php application and prevents you from easily using LIMIT in your queries.
You should store the per-user permissions in the database table, and then use a join so that only the articles that a user can view are retrieved. Then you don’t have to handle the pagination or sorting logic in your application; you can just use LIMIT and ORDER BY in mysql to do it for you.
Also you should probably use the parameter-based queries. Your code has a massive sql injection hole.