Logo  

CS479/579 - Web Programming II

Lesson 7

A paginated output example:

<?php
$page = isset($_GET['page'])? (int)$_GET['page'] : 0;
$start = $page * 10;

if (isset($_GET['xpage']) && $_GET['xpage'] != "") {
  $page = (int)$_GET['xpage'];
}

$dir = isset($_GET['dir'])? (int)$_GET['dir'] : 0;
$ndir = $dir ^ 1;

$cols = ["uid", "username", "gecos"];
$col = isset($_GET['col'])? (int)$_GET['col'] : 0;
if ($col < 0 || $col > 5) $col = 0;
else if ($col > 2) {
  $col = $col - 3;
  $dir = 0;
}
$order = $cols[$col] . " " . ($dir == 0? "ASC" : "DESC");

$conn = new mysqli("localhost", "sbaker", "sbaker", "sbaker") or
  die("Error connecting to database.\n");
?>
<!DOCTYPE html>
<html>
<head>
 <title> PW list </title>
 <meta charset='utf-8'>
 <style>
 table {
   margin-left: 5pc;
   padding: 2mm;
   border: 1mm solid black;
 }
 th { text-align: left; }
 tr:nth-child(4n+1) td, tr:nth-child(4n+2) td {
   background: lightblue;
 }
 td { min-width: 15vw; }
 td:last-child { min-width: 50vw; }
 input[type=number] { width: 1cm; }
 </style>
</head>
<body>
<form method=get>
<?php
  if ($col > 0) echo "<input type=hidden name=col value=$col>\n";
  if ($dir > 0) echo "<input type=hidden name=dir value=$dir>\n";
  if ($page > 0) echo "<input type=hidden name=page value=$page>\n";
?>
<table>
<thead>
<tr><th><?php
 if ($col == 0) {
  echo "<button name='dir' value=$ndir>UID</button>";
  if (!$dir) echo "&#x25BC;";
  else echo "&#x25B2;";
 } else {
  echo "<button name='col' value=3>UID</button>";
 }
?>
<th><?php
 if ($col == 1) {
  echo "<button name='dir' value=$ndir>Username</button>";
  if (!$dir) echo "&#x25BC;";
  else echo "&#x25B2;";
 } else {
  echo "<button name='col' value=4>Username</button>";
 }
?>
<th><?php
 if ($col == 2) {
  echo "<button name='dir' value=$ndir>Real Name</button>";
  if (!$dir) echo "&#x25BC;";
  else echo "&#x25B2;";
 } else {
  echo "<button name='col' value=5> Real Name</button>";
 }
?>
</thead>
<tbody>
<?php
// Make sure bound variables exist before binding:
$uid = $username = $gecos = null;

$stmt = $conn->prepare("SELECT username, uid, gecos FROM passwd ORDER BY $order LIMIT ?,11");
$stmt->bind_param("i", $start);
$stmt->bind_result($username, $uid, $gecos);
$stmt->execute();

$i = 0;
while($i < 10 && $stmt->fetch()) {
  $i++;
  printf("<tr><td>%d <td>%s <td>%s\n", (int)$uid, $username, explode(",",$gecos)[0]);
}
if ($stmt->fetch()) $next = $page + 1;
else $next = $page;

$stmt->close();
?>
<tfoot>
<tr>
<td>
<?php if ($page > 0):?>
 <button name='page' value='<?php echo max($page-1,0); ?>'> Prev </button>
<?php endif; ?>
<td>Page: <?php echo $page; ?> <input type=number name='xpage'>
<td>
<?php if ($next != $page):?>
<button name='page' value='<?php echo $next; ?>'> Next </button>
<?php endif; ?>
</tfoot>
</tbody>
</table>
</form>
</body>
</html>