Pagination Tutorial - Page Existence Check

Post here is you are having problems with any of the tutorials.
Post Reply
nyo
Posts: 124
Joined: Mon May 09, 2011 1:55 pm
Location: Mobile

Pagination Tutorial - Page Existence Check

Post by nyo »

I was going to ask this as a question but I tried a bit more and I was able to solve it myself. I am posting this because others might need this as well.

I went through the Pagination tutorial (http://betterphp.co.uk/playlist.html?pi ... 4EA7CE6B37) and everything worked fine. There was one issue though. When you insert an integer other than (1,2,3) into the ?page= part, it gave errors. For example when you leave it empty or insert 4 or 0, it gave the following errors:

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\Apache2\htdocs\pagination\user_list.php on line 16
Notice: Undefined variable: users in C:\Apache2\htdocs\pagination\user_list.php on line 19
Warning: Invalid argument supplied for foreach() in C:\Apache2\htdocs\pagination\user_list.php on line 28


What I did is to insert a check whether the page exists or not and send the user to the first page if the page doesn't exist. The following may not be the best solution, but it worked for me.

I removed this part:
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
and inserted an if-else check for the existence of the page. The page value should be greater or equal to "1" and less than or equal to "$total_pages". And here is the final code:
<?php 
$db = mysql_connect('localhost', '...', '...');
mysql_select_db('...');
mysql_set_charset('utf8', $db);

function fetch_total_users () {
	$result = mysql_query("SELECT COUNT(`user_id`) FROM `users`");
	return mysql_result($result, 0);
}

/* Defined $total_pages here so that I could use it in the if statement. */

$total_pages = ceil(fetch_total_users() / 5);

/* If the page value is between 1 and $total_pages, send the user to the page requested, else, send them to page 1. */

if (isset($_GET['page'])) {
	if ($_GET['page'] >= 1 && $_GET['page'] <= $total_pages) {
		$page = (int)$_GET['page'];
	} else {
		$page = 1;
	}
} else {
	$page = 1;
}

function fetch_users($page, $per_page) {
	$start    = (int)($page - 1) * $per_page;
	$per_page = (int)$per_page;
	
	$query = mysql_query("SELECT `user_name` FROM `users` LIMIT {$start}, {$per_page}");
	while ($row = mysql_fetch_assoc($query)) {
		$users[] = $row['user_name'];
	}
	return $users;
}
	foreach (fetch_users($page, 5) as $user) {
		echo "<p>{$user}</p>";
	}
	
	for ($i = 1; $i <= $total_pages; ++$i) {
		echo "<a href=\"?page={$i}\">{$i}</a> ";
	}
?>
Post Reply