Reputation: 1023
I have put together a method of separating the output of a mysql query with PHP so that the results come back in groups, separated by pages (so, page 0 has posts 1 through 10, page 1 has posts 11 through 20, and so forth).
The URL passes a variable like so;
http://domain.com/test.php?page=0 (this will render results 1 through 10)
The value of 0 is used in the MySQL query for that particular page, which looks like this;
$page = $_GET['page'];
select <search> limit $page, 10; (this has been made brief to spare you the superfluous details).
So, the challenge is to take this value that is passed from the URL to the query in order to render the proper results for that page. I figured out a way to do it, but frankly I am unhappy with it and I can't help but have the feeling that it will eventually have problems.
if ($page == "0")
{
$page = 0;
}
elseif ($page == "1")
{
$page = 10;
}
elseif ($page == "2")
{
$page = 20;
}
elseif ($page == "3")
{
$page = 30;
}
elseif ($page == "4")
{
$page = 40;
}
elseif ($page == "5")
{
$page = 50;
}
elseif ($page == "6")
{
$page = 60;
}
Like I said, this seems to work, but is there a smarter way to do this? I need to change the value more efficiently and also, hopefully, find a way so that if I change my mind tomorrow and decide to render 15 posts per page instead that it will not be difficult.
Upvotes: 0
Views: 79
Reputation: 76656
You can use a function like this:
function getNum($page) {
return (int) $page * 10;
}
And use it like:
$page = getNum($page);
This is a good practice if you want to do it multiple times. And organizing your logic into a function makes it easier to update code in future. You don't need to modify the logic in every single statement. Modifying one single function would be enough.
Type-casting to int
will also make sure only numbers are inserted into your query.
But however, you should still escape the user input properly before inserting it into your database (preferred way is to use MySQLi or PDO with parameterized queries).
Upvotes: 3
Reputation: 25384
Uhm... Maybe I'm missing something obvious, but why don't you just do this?
$page = $page * 10;
If you decide to render 15 posts per page tomorrow, just change it to fifteen.
Upvotes: 6