简体   繁体   中英

Pagination with Javascript, Php & MySQL

I'm trying to build a simple news page based on this tutorial

http://www.prashantblog.com/use-ajax-filter-mysql-results-set/

It gets data from the database and creates divs for each section, and will filter the results depending on which checkbox is ticked.

I need to limit the results showed to 10 maxiumum, and then add pagination so they user can go to the next page of results, but still the results filtered if they have clicked on a checkbox.

I'm a bit confused on how the logic will work and what I need to do to get the pagination working.

Javascript:

var base_href = '/go/media~';

function makeTable(data) {
  var tbl_body = "";
  $.each(data, function (index, row) {
    var tbl_row = "";
    $.each(row, function (k, v) {
      if (k == 'heading' && 'id' in row) {
        v = '<h2><a class="news" href="' + base_href + row.id + '">' + v + '</a></h2>';
      }
      if (k == 'id' in row) {
        v = '<div style="display:none">' + v + '</div>';
      }
      tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>"
        + v + "   </div></div>";

    });
    tbl_footer = '<div class="row read-more"><div class="col-md-8 col-md-offset-2"><a href="' + base_href + row.id + '">Read more</a></div></div>';
    tbl_body += "<div class='non-white-media'>" + tbl_row + tbl_footer + "</div>";

  });

  return tbl_body;
}

function getEmployeeFilterOptions() {
  var opts = [];
  $checkboxes.each(function () {
    if (this.checked) {
      opts.push(this.name);
    }
  });

  return opts;
}

function updateEmployees(opts) {
  $.ajax({
    type: "POST",
    url: "filter3.php",
    dataType: 'json',
    cache: false,
    data: {filterOpts: opts},
    success: function (records) {
      $('#employees div').html(makeTable(records));
    }
  });
}

var $checkboxes = $("input:checkbox");

$checkboxes.on("change", function () {
  var opts = getEmployeeFilterOptions();
  updateEmployees(opts);
});

updateEmployees();

Filter3.php

<?php

$pdo = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
$select = 'SELECT id, heading, summary, created_date';
$from = ' FROM media';
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts']) ? $_POST['filterOpts'] : array('');
if (in_array("article", $opts)) {
    $where .= " AND article = 1";
}
if (in_array("press_release", $opts)) {
    $where .= " AND press_release = 1";
}
if (in_array("video", $opts)) {
    $where .= " AND video = 1";
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
  1. Create a variable to results limit ($limit = 10)
  2. Create a "page" GET parameter
  3. Use mysql "LIMIT [offset],[count]" clause to filter the rows. Offset is the number of rows skiped: $offset = $limit * $page;

Filter3.php will be something like:

$limit = 10;
$page = intval($_GET["page"]);

$pdo = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
$select = 'SELECT id, heading, summary, created_date';
$from = ' FROM media';
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts']) ? $_POST['filterOpts'] : array('');
if (in_array("article", $opts)) {
    $where .= " AND article = 1";
}
if (in_array("press_release", $opts)) {
    $where .= " AND press_release = 1";
}
if (in_array("video", $opts)) {
    $where .= " AND video = 1";
}

$offset = $page * $limit; //skip rows from previous pages
$limit = " LIMIT $offset,$limit";

$sql = $select . $from . $where;

$sql .= $limit;

$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);

Then you can use the "page" parameter to put links in HMTL/javascript to navigate between pages.

Attention: Consider refactoring the way you do database connection (not hardcode credentials in code) and fill the parameters (the correct way is to parametrize your query and parse/check all parameters received from client).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM