【发布时间】:2020-04-11 12:50:52
【问题描述】:
我坚持在我的 PHP MVC 应用程序中实现分页。 这是我为展示我的产品所做的,现在我完全陷入困境,因为我不知道如何在我的代码中实现分页。 我希望有人会用我的代码向我展示示例,以便我将来学习;
我的控制器->Products.php
<?php
/**
*
*/
class Products extends Controller
{
public function __construct()
{
if(!isLoggedIn()){
redirect('users/login');
}
$this->productModel = $this->model('Product');
}
public function index(){
$products = $this->productModel->getProducts();
$data=[
'products' => $products
];
$this->view('products/index', $data);
}
}
我的模型->Product.php
<?php
/**
*
*/
class Product
{
public function __construct()
{
$this->db = new Database();
# code...
}
public function getProducts(){
$this->db->query('SELECT *,
products.id as productId,
users.id as userId,
products.productCreated as productCreated,
users.created_at as userCreated
FROM products
INNER JOIN users
ON products.user_id = users.id
ORDER BY products.productCreated DESC
');
$results = $this->db->resultSet();
return $results;
}
}
和我的观点 Product->Index.php
<?php require APPROOT . '/views/inc/header.php'; ?>
<style type="text/css">
#abc {
line-height: 2px;
}
#productName {
font-size: 14px;
font-weight: bold;
line-height: 10px;
padding-top: 6px;
}
#cardid {
margin-top: 15px;
}
#buybtn {
width: 100px;
height: 30px;
margin-top: -10px;
padding: 2px;
}
</style>
<div class="container-fluid">
<h1> PRODUCTS</h1>
<div class="row">
<div class="col-lg-10">
<?php foreach ($data['products'] as $product) : ?>
<div class="card" style="width: 150px; text-align:center;display:inline-block;" id="cardid">
<h4 class="card-title text-center" id="productName"><?php echo $product->productName; ?></h4>
<img class="card-img-top" src="img/img_avatar1.png" alt="Card image" style="width:100%">
<div class="card-block">
<p class="card-text">Some example text some example text. John Doe is an architect and engineer</p>
<p class="card-text" id="abc" style="color:red">125</p>
<a href="#" class="btn btn-primary stretched-link" id="buybtn">Buy now</a>
</div>
</div>
<?php endforeach; ?>
</div>
<div class="col-lg-2 jumbotron">
Container Right
</div>
</div>
</div>
<?php require APPROOT . '/views/inc/footer.php'; ?>
我看到很多关于分页的帖子,但我不知道如何在这里实现它,所以我每页只能显示 10 个产品...
【问题讨论】:
-
通常您可能希望在视图/url 中添加一个附加参数,例如
www.example.com/posts/1,其中 1 是页面#。在您的 php 代码中,您可以获取此值以将 LIMIT 和 OFFSET 的组合添加到您的查询中。即如果请求是针对www.example.com/posts/12,您的查询将是`SELECT * from ... LIMIT 10 OFFSET ({12 - 1}* 10)
标签: php html css pagination