I have created a JSON file with the following fields:
Name| Age| Gender
There are total 50 records. Here I require 2 functionalities.
- Display 10 records per page and
- Cycle through records using NEXT and PREV buttons only.
I tried searching but everyone has tried with mysql and javascript which I have tried and got so many errors. So, can anyone help me with this.
This is the php code I’ve used:
<?php $emp = file_get_contents('employee.json'); $emp = json_decode($emp,true); $page = !isset($_GET['page']) ? 1 : $_GET['page']; $limit = 5; $offset = ($page - 1) * $limit; $total_items = count($emp['employee']); $total_pages = ceil($total_items / $limit); $array = array_splice($emp['employee'], $offset, $limit); for($j=1;$j<=$total_pages;$j++) { echo "<span><a href='json.php?page=$j'>$j</a></span>"; } foreach($emp['employee'] as $emps){ ?> <tr> <td><?php echo $emps['name']; ?></td> <td><?php echo $emps['gender']; ?></td> <td><?php echo $emps['designation']; ?></td> </tr> <?php } ?>
Here I have encountered the following errors:
- All the records are displayed in the page and even it is repeating in the next page.
- Here I wanted to insert the Next and previous buttons instead of the page numbers.
This is the result I have got till now: sample
Advertisement
Answer
Here’s something you can build on. Of course you can’t just copy and paste – that makes it harder to be sure that the required understanding has sunk-in! I’ve written it quick-n-dirty. You can extract the required logic AND add some error checking…
data.json
[ {"name": "name1", "gender": "male", "title": "junior dev"}, {"name": "name2", "gender": "female", "title": "junior dev"}, {"name": "name3", "gender": "unicorn", "title": "junior dev"}, {"name": "name4", "gender": "toaster", "title": "junior dev"}, {"name": "name5", "gender": "pineapple", "title": "junior dev"} ]
showResults.php
<!doctype html> <html> <head> <style> thead{ background-color: #888; color: #fff; } th{ padding: 4px 8px; } td{ padding: 4px; } </style> </head> <body> <?php $filename = "data.json"; $rawData = file_get_contents($filename); $dataArray = json_decode($rawData,true); $pageNum = 0; if (isset($_GET['page'])) $pageNum = $_GET['page']; $recordCount = count($dataArray); $itemsPerPage = 2; $maxPage = floor($recordCount / $itemsPerPage) - 1; ?> <table> <thead> <tr><th>Name</th><th>Gender</th><th>title</th></tr> </thead> <tbody> <?php $firstRecordIndex = $pageNum * $itemsPerPage; for ($index = $firstRecordIndex; $index < ($firstRecordIndex+$itemsPerPage); ++$index) { if (isset($dataArray[$index])) printf("<tr><td>%s</td><td>%s</td><td>%s</td></tr>", $dataArray[$index]['name'], $dataArray[$index]['gender'], $dataArray[$index]['title']); } ?> </tbody> </table> <a href='showResults.php?page=<?php print( max(0,$pageNum-1));?>'>Prev</a> </body> </html>