后端php查询所有数据,前端通过ajax请求获取并且动态生成带有分页的表格
前端html代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Document</title>
<style>
.active{
color: green;
}
.modal{
width: 550px;
position: absolute;
top: 0;
background-color: skyblue;
display: none;
}
a{
text-decoration: none;
color: #000;
}
</style>
</head>
<body>
<table>
<caption>员工列表</caption>
<thead>
<tr>
<th>id</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>邮箱</th>
<th>生日</th>
<th>入职日期</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<p class="page">
</p>
<div class="modal">
<button class="close">关闭</button>
<form action="" method="POST" id="edit">
<p><label for="">姓名:<input type="text" value="" name="name" id="name" /></label></p>
<p><label for="">性别:<select name="gender" id="gender">
<option value="male">男</option>
<option value="female">女</option>
</select>
</label></p>
<p> <label for="">年龄:<input type="text" value="" name="age" id="age" /></label></p>
<p><label for="">邮箱:<input type="email" value="" name="email" id="email" /></label></p>
<p><label for="">生日:<input type="text" value="" name="borthday" id="borthday" /></label></p>
<input type="hidden" value="" name="id" id="id" />
<p> <label for=""><button class="save">保存</button></label></p>
</form>
</div>
</body>
<script>
select(1);
function show(data) {
var html = '';
$.each(data, function(index, value) {
html += '<tr>';
html += '<td>' + data[index]['id'] + '</td>';
html += '<td>' + data[index]['name'] + '</td>';
html += '<td>' + data[index]['gender'] + '</td>';
html += '<td>' + data[index]['age'] + '</td>';
html += '<td>' + data[index]['email'] + '</td>';
html += '<td>' + data[index]['borthday'] + '</td>';
html += '<td>' + data[index]['create_time'] + '</td>';
html += '<td><button class="edit" data-index='+data[index]['id']+'>编辑</button><button class="del"data-index='+data[index]['id']+'>删除</button></td>';
html += '</tr>';
})
return html;
}
// 查询
function select(page = 1) {
$.get("http://127.0.0.119/pdo/limit.php?action=select&p=" + page, function(res) {
var obj = jQuery.parseJSON(res);
let pages = obj.pages;
let rows = obj.rows;
console.log(rows);
$('tbody').html(show(rows));
$('.page').html(getPage(page, pages));
})
}
function getPage(page = 1, pages) {
let p = "";
let active = "";
// 首页|上一页
if (page <= 1) page = 1;
if (page !== 1) {
p += '<a href="http://127.0.0.119/pdo/limit.php?action=select&p=1">首页</a>';
p += '<a href="http://127.0.0.119/pdo/limit.php?action=select&p= '+ Math.max(1, page - 1) + '">上一页</a>';
}
// 高亮
for (i = 1; i <= pages; i++) {
active = "";
if (page == i) active = 'class="active"';
p += '<a href="http://127.0.0.119/pdo/limit.php?action=select&p=' + i+ '"'+ active + '>' + i + '</a>';
}
// 下一页|尾页
if (page >= pages) page = pages;
if (page != pages) {
p += '<a href="http://127.0.0.119/pdo/limit.php?action=select&p=' + ( parseInt(page) +1 ) + '">下一页</a>';
p += '<a href="http://127.0.0.119/pdo/limit.php?action=select&p=' + pages + '">尾页</a>';
}
return p;
}
$('.page').on('click',
function(event){
event.preventDefault();
event.stopPropagation();
let page=$(event.target).attr('href');
page=page.split('=')[2];
select(page);
}
);
//编辑
$(' tbody').on('click','.edit',function(){
let id=$(this).attr('data-index');
$.get("http://127.0.0.119/pdo/limit.php?action=getOne&id=" + id, function(res) {
var obj = jQuery.parseJSON(res);
let rows = obj.rows;
let name=rows.name;
let gender=rows.gender;
let age=rows.age;
let email=rows.email;
let borthday=rows.borthday;
let id=rows.id;
$('#name').val(name);
if (gender=='male'){
$('#gender option').removeAttr('selected');
$('#gender option:nth-of-type(0)').attr('selected',true);
}else{
$('#gender option').removeAttr('selected');
$('#gender option:nth-of-type(2)').attr('selected',true);
}
$('#age').val(age);
$('#email').val(email);
$('#borthday').val(borthday);
$('#id').val(id);
$('.modal').show();
});
});
$('.close').click(()=>{
$('.modal').hide();
})
//保存
$('.save').on('click',function(event){
event.preventDefault();
$.post("http://127.0.0.119/pdo/limit.php?action=save", $("#edit").serialize(),function(data){
alert(data);
$('.modal').hide();
location.reload();
});
})
//删除
$(' tbody').on('click','.del',function(){
let id=$(this).attr('data-index');
$.get("http://127.0.0.119/pdo/limit.php?action=delete&id=" + id, function(res) {
location.reload();
alert(res);
});
});
</script>
</html>
后端php代码
$config = [
'type' => 'mysql',
'host' => '127.0.0.1',
'dbname' => 'php',
'port' => 3306,
'charset' => 'utf8mb4',
'username' => 'root',
'passwrod' => '123456',
];
extract($config);
$dsn = sprintf('%s:dbname=%s;', $type, $dbname);
try {
$pdo = new PDO($dsn, $username, $passwrod);
//设置结果集的返回类型
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die('连接失败' . $e->getMessage());
}
//计算共计多少页?
$action = $_GET['action'] ?? 'select';
$page = $_GET['p'] ?? 1;
$id = $_GET['id'] ?? 1;
$data = $_POST;
switch ($action) {
case 'select':
select($pdo, $page);
break;
case 'getOne':
getOne($pdo, $id);
break;
case 'save':
save($pdo, $data);
break;
case 'delete':
delete($pdo, $id);
break;
}
//查询所有数据
function select($pdo, $page = 1, $num = 5)
{
//计算当前页的起始偏移量
$offset = ($page - 1) * $num;
//ceil()向上取整
$sql = "SELECT CEIL(COUNT(1)/{$num}) total FROM user";
$row = $pdo->query($sql);
$pages = $row->fetch()['total'];
// print_r($row);
//每页显示的数据
$sql = "SELECT * FROM `user` LIMIT {$offset},{$num}";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll();
echo json_encode(['pages' => $pages, 'rows' => $rows]);
}
//获取单条信息
function getOne($pdo, $id)
{
$sql = "SELECT * FROM user WHERE id={$id}";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$rows = $stmt->fetch();
echo json_encode(['rows' => $rows]);
}
//更新数据
function save($pdo, $data)
{
$sql = "UPDATE `user` SET name = :name, gender = :gender, age = :age, email = :email, borthday = :borthday WHERE id=:id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $data['name'], PDO::PARAM_STR);
$stmt->bindParam(':gender', $data['gender'], PDO::PARAM_STR);
$stmt->bindParam(':age', $data['age'], PDO::PARAM_STR);
$stmt->bindParam(':email', $data['email'], PDO::PARAM_STR);
$stmt->bindParam(':borthday', $data['borthday'], PDO::PARAM_STR);
$stmt->bindParam(':id', $data['id'], PDO::PARAM_INT);
$stmt->execute();
if ($stmt->rowCount() > 0) {
echo '更新成功';
} else {
echo '更新失败';
}
}
//删除数据
function delete($pdo, $id)
{
$sql = "DELETE FROM `user` WHERE id=:id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
if ($stmt->rowCount() > 0) {
echo '删除成功';
} else {
echo '删除失败';
}
}
效果图