添加一个搜索
[PHP] 纯文本查看 复制代码 <?php
try {
$dsn = "mysql:host=localhost;dbname=数据库名";
$username = "数据库名";
$password = "数据库密码";
$pdo = new PDO($dsn, $username, $password);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// 处理搜索关键字
$keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
// 计算总记录数
$sql = "SELECT COUNT(1) FROM `表名`" . ($keyword ? " WHERE `产品名` LIKE '%$keyword%'" : "");
$total = $pdo->query($sql)->fetchColumn();
// 每页显示记录数
$pageSize = 10;
// 计算总页数
$pageCount = ceil($total/$pageSize);
// 当前页码,默认为第一页
$pageNum = isset($_GET['page']) ? $_GET['page'] : 1;
// 起始记录数
$start = ($pageNum - 1) * $pageSize;
// 查询分页数据
$sql = "SELECT * FROM `表名`" . ($keyword ? " WHERE `产品名` LIKE '%$keyword%'" : "") . " LIMIT {$start},{$pageSize}";
$stmt = $pdo->query($sql);
$list = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP+Layui分页+搜索</title>
<link rel="stylesheet" >
</head>
<body>
<div class="layui-container">
<br>
<form class="layui-form" action="" method="get">
<div class="layui-inline">
<input type="text" name="keyword" placeholder="请输入产品名" value="<?php echo htmlspecialchars($keyword); ?>" class="layui-input">
</div>
<button class="layui-btn" lay-submit lay-filter="search"><i class="layui-icon layui-icon-search"></i></button>
<a href="?page=1" class="layui-btn layui-btn-primary">重置</a>
</form>
<br>
<table class="layui-table">
<thead>
<tr>
<th>ID</th>
<th>产品名</th>
<th>产品库存</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php foreach($list as $vo){ ?>
<tr>
<td><?php echo $vo['id']; ?></td>
<td><?php echo $vo['产品名']; ?></td>
<td><?php echo $vo['产品库存']; ?></td>
<td><a href="delete.php?id=<?php echo $vo['id']; ?>">删除</a></td>
</tr>
<?php } ?>
</tbody>
</table>
<div id="demo"></div>
</div>
<script src="https://cdn.staticfile.org/layui/2.5.6/layui.min.js"></script>
<script>
layui.use(['laypage', 'form'], function(){
var laypage = layui.laypage;
var form = layui.form;
// 渲染分页导航栏
laypage.render({
elem: 'demo',
count: <?php echo $total; ?>,
limit: <?php echo $pageSize; ?>,
curr: <?php echo $pageNum; ?>,
jump: function(obj, first){
if(!first){
// 点击页码时,重新加载页面
window.location.href = '?page=' + obj.curr + '&keyword=<?php echo urlencode($keyword); ?>';
}
}
});
// 监听搜索表单提交事件
form.on('submit(search)', function(data){
window.location.href = '?keyword=' + data.field.keyword;
return false;
});
});
</script>
</body>
</html> |