gpt4 book ai didi

php - 如何向现有代码添加分页?

转载 作者:行者123 更新时间:2023-11-29 09:54:31 24 4
gpt4 key购买 nike

我想向我使用 ajax 编程的现有表添加分页。

我尝试了多种分页解决方案,但没有一个看起来与我现在拥有的现有表格兼容

index.php 中的表

<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<th width="5%"></th>
<th width="10%">Serial No.</th>
<th width="20%">Equipment Type</th>
<th width="15%">Document Remarks</th>
<th width="10%">Supplier</th>
<th width="10%">Date In</th>
<th width="10%">Customer</th>
<th width="10%">Date Out</th>
</thead>
<tbody></tbody>
</table>
</div>

在index.php中显示表格的脚本

<script>
$(document).ready(function () {

function fetch_data()
{
$.ajax({
url: "select.php",
method: "POST",
dataType: "json",
success: function (data)
{
var html = '';
for (var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td><input type="checkbox" value="' +
data[count].id + '" id="' + data[count].id + '" data-serial_number="' +
data[count].serial_number + '" data-equipment_type="' +
data[count].equipment_type + '" data-document_remarks="' +
data[count].document_remarks + '" data-supplier="' + data[count].supplier +
'" data-date_scan="' + data[count].date_scan + '" data-customer="' +
data[count].customer + '" data-date_out="' + data[count].date_out + '"
class="check_box" /></td>';
html += '<td>' + data[count].serial_number + '</td>';
html += '<td>' + data[count].equipment_type + '</td>';
html += '<td>' + data[count].document_remarks + '</td>';
html += '<td>' + data[count].supplier + '</td>';
html += '<td>' + data[count].date_scan + '</td>';
html += '<td>' + data[count].customer + '</td>';
html += '<td>' + data[count].date_out + '</td></tr>';
}
$('tbody').html(html);
}
});
}

fetch_data();
}
</script>

选择.php

include('database_connection.php');

$query = "SELECT * FROM inventory ORDER BY id DESC";

$statement = $connect->prepare($query);

if ($statement->execute()) {
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}

echo json_encode($data);
}
?>

最佳答案

在您的 fetch_data() 函数中,您需要在 POST 请求中包含页面数据:

  • limit 应该是每页可查看的项目数
  • offset 应为 limit 乘以页码(从 0 开始)

例如。下面将请求第二页结果(每页 10 个结果)

$.ajax({
url: "select.php",
method: "POST",
dataType: "json",
data: {limit: 10, offset: 10},
// etc.

在您的 PHP 脚本中,您需要读取这些变量并将它们添加到您的查询中:

$limit = $_POST['limit'];
$offset= $_POST['offset'];

$query = "SELECT * FROM inventory ORDER BY id DESC LIMIT = ? OFFSET= ?";
$statement = $connect->prepare($query);

if ($statement->execute([$limit, $offset])) {
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}

echo json_encode($data);
}

关于php - 如何向现有代码添加分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54102604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com