vendredi 13 février 2015

PHP PDO Pagination issue

Having an issue with results being displayed. I retrieve "« ‹ Page 1 of 1 pages, displaying 1-2 of 16 results › »" correctly but the results are not being printed to my table from my foreach loop. Any Suggestions?


Index.php



<?php
include 'insert.php';
include 'database.php';
try {

// Find out how many items are in the table
$result = $conn->query('
SELECT
COUNT(*)
FROM
stock
')->fetchColumn();

// How many items to list per page
$limit = 10;

// How many pages will there be
$pages = ceil($result / $limit);

// What page are we currently on?
$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default' => 1,
'min_range' => 1,
),
)));

// Calculate the offset for the query
$offset = ($page - 1) * $limit;

// Some information to display to the user
$start = $offset + 1;
$end = min(($offset + $result), $result);

// The "back" link
$prevlink = ($page > 1) ? '<a href="?page=1" title="First page">&laquo;</a> <a href="?page=' . ($page - 1) . '" title="Previous page">&lsaquo;</a>' : '<span class="disabled">&laquo;</span> <span class="disabled">&lsaquo;</span>';

// The "forward" link
$nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">&rsaquo;</a> <a href="?page=' . $pages . '" title="Last page">&raquo;</a>' : '<span class="disabled">&rsaquo;</span> <span class="disabled">&raquo;</span>';

// Display the paging information
echo '<div id="paging"><p>', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $result, ' results ', $nextlink, ' </p></div>';

// Prepare the paged query
$stmt = $conn->prepare('
SELECT
*
FROM
stock
ORDER BY
ItemCode
LIMIT
:limit
OFFSET
:offset
');

// Bind the query params
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();

// Do we have any results?
if ($stmt->rowCount() > 0) {
// Define how we want to fetch the results
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt);

// Display the results
echo "<table><tr><th>Item Code:</th><th>Quantity:</th><th>Range:</th><th>Gender:</th><th>Type:</th><th>Size:</th><th>Catalogue:</th></tr>";
foreach ($result as $row) {
echo "<tr><td>" . $row['ItemCode'] . "</td>";
echo "<td>" . $row['Quantity'] . "</td>";
echo "<td>" . $row['Range'] . "</td>" ;
echo "<td>" . $row['Gender'] . "</td>" ;
echo "<td>" . $row['Type'] . "</td>" ;
echo "<td>" . $row['Size'] . "</td>" ;
echo "<td>" . $row['Catalogue'] . "</td></tr>" ;
}
echo "</table>";

} else {
echo '<p>No results could be displayed.</p>';
}

} catch (Exception $e) {
echo '<p>', $e->getMessage(), '</p>';
}

?>

Aucun commentaire:

Enregistrer un commentaire