6.9PHP分页与更新数据
分页
<?php
$keywords = isset($_GET['keywords'])?$_GET['keywords']:'';
//建立变量搜索关键字,当可以get到keywords时给它赋值,没有时为空,不对筛选造成影响
$page = isset($_GET['page'])?$_GET['page']:1;
//当前页码
$znum = 3;
//分页后每页的行数
$sqlnum = ($page-1)*$znum.','.$znum;
//用.拼接字符串,成为limit对象
$conn = new mysqli('localhost','root','root','ceshi');
$sql = "select * from product where title like '%$keywords%' limit $sqlnum";
$res = $conn->query($sql);
$list = $res->fetch_all(MYSQLI_ASSOC);
//连接数据库后将关键字作为查找条件
$sql = "select * from product where title like '%$keywords%'";
$zongnum = $conn->query($sql);
$zongnum = $zongnum->num_rows;
$zpage = ceil($zongnum/$znum);
//计算总页数,这里使用了ceil()向上取整
$conn->close();
?>
var laypage = layui.laypage;
//layui分页
laypage.render({
elem: 'test1',
//确定对象,这里test1指的是id
count: <?php echo $zongnum;?>,
//确定数据总数
limit: <?php echo $znum;?>,
//确定如何分页
curr: <?php echo $page;?>,
//确定当前页
jump: function(obj,frist){
if(!frist){//首次不执行
console.log(obj.curr);
location.href = 'product.php?page='+obj.curr+'$keywords=<?php echo $keywords;?>';
}
}
})
在html适当位置加入
<div id="test1"></div>即可显示
更新数据
<?php
$id = $_GET['id'];
$conn = new mysqli('localhost','root','root','ceshi');
if ($_POST){
$title = trim($_POST['title']);
$uname = $_POST['img'];
$descs = $_POST['desc'];
$content = $_POST['content'];
$conn = new mysqli('localhost','root','root','ceshi');
$sql = "update product set title='$title',img='$uname',descs='$descs',content='$content' where id = $id ";
//如当时添加新数据,不过这里的sql语句是update更新数据
$res = $conn->query($sql);
//执行sql语句
if($conn->error){
die($conn->error);
}
if($res){
header('location: product.php');
//完成后跳转到产品展示界面
}else{
echo $res;
}
}
$sql = "select * from product where id = $id";
$res = $conn->query($sql);
$info = $res->fetch_assoc();
$conn->close();
?>
更新数据的界面需要在html文件中添加mysql中的数据,方便修改