Logo  

CS479/579 - Web Programming II

Displaying exercises/e7/solution/pkglist.php

<?php
 include "config.php";

 // Get page number, default to page 0:
 $page = isset($_GET['page'])? ((int)$_GET['page']) : 0;
 // Previous page has a minimum value of 0:
 $prev = max(0, $page-1);
 $next = $page;
 $p = $page*20;

 // Prepare the SQL statement and execute it, it will be read below as we create the table:
 $stmt = $myconn->prepare("SELECT `id`, `name`, `desc` FROM pkgs ORDER BY name ASC LIMIT ?, 21");
 if ($stmt == false) die("prepare" . $myconn->error);

 $stmt->bind_param("i", $p);
 $stmt->bind_result($id, $name, $desc);
 $stmt->execute();
?>
<!DOCTYPE html>
<html>
<head>
 <title> Package list </title>
 <meta charset='utf-8'>
 <style>
  body { font-family: 'Arial'; font-size: 16pt; }
  a:link, a:visited { text-decoration : none; color: black; }
  tbody tr:nth-child(odd) { background: #DDD; }
  tbody tr { height: 30px; }
  th:first-child, td:first-child { width: 450px; max-width: 450px; }
  th:last-child, td:last-child { width: 600px; max-width: 600px; }
  td {
    text-overflow: clip; white-space: nowrap; overflow: hidden;
  }
 </style>
</head>
<body>
<h1> Slackware Packages </h1>
<table>
<thead>
 <tr><th> Package name <th style='width:600px;'> Description
</thead>
<tbody>
<?php
 // Fetch the data from the above prepared statement, $r keeps count of the
 // number of records we've printed:
 for($r = 0; $r < 20 && $stmt->fetch(); $r++) {
   echo "<tr><td><a href='pkgdesc.php?id={$id}'> {$name} </a>";
   echo "<td><a href='pkgdesc.php?id={$id}'> {$desc} </a>\n";
 }
 // If we can fetch a 21st record, we know we have at least one more page of
 // data:
 if ($r == 20 && $stmt->fetch()) $next = $page+1;
 $stmt->close();

 // This fills out the rest of the table for 20 rows in case we have fewer than
 // 20 records:
 while ($r < 20) {
   echo "<tr><td><td>";
   $r++;
 }
?>
</tbody>
<tfoot>
<form method=GET>
 <tr>
  <td><button type=submit name='page' value='<?php echo $prev;?>'> Prev </button>
  &nbsp; Displaying page <?php echo "$page";?>
  <td><button type=submit name='page' value='<?php echo $next;?>'> Next </button>
</form>
</tfoot>
</table>
</body>
</html>