Saturday, July 16, 2011

Pagination; SQL vs Based

Whenever I write PHP, I try my hardest to avoid using MySQL. I think it's a hassle and it should be avoided at all costs. So, I usually try to come up with a way to "base" my PHP scripts. Basing means I can call accounts, pages, or whatever without the use of a MySQL database.

Now one of the most popular things that people do with MySQL databases is create Pagination scripts (think index.php?id=1 and index.php?page=derp).

When they use a database, they have their PHP script search the table for the relevant page (AKA "dork") and it will display it accordingly. Simple, right?



Now there are multiple ways to call a page in without using MySQL, and I'll post two ways.

Way #1: Arrays (This way is better in my opinion)

<?php
// Whitelist of valid includes
$Pages = array("links", "projects", "contact", "404");
if (in_array($_GET['id'], $Pages))
{
include $_GET['id'] . ".php";
}
else
{
// 404 code goes here, or echo some HTML
}
?>


Way #2: A series of if-else statements

<?php
$id = $_GET['id'];
if ($id == 'links')
{
include 'links.php';
}
else if ($id == 'privacy')
{
include 'privacy.php';
}
else if ($id =='contact')
{
include 'contact.php';
}
else
{
//404 page here, or echo some HTML
}
?>



Feel free to use either of those snippets, no credit is needed.


If you know any other based pagination methods, please tell me!

1 comment:

  1. Interesting, im a total noob though so i guess its kinda hard to grasp that stuff.

    ReplyDelete