我正在 CodeIgniter 中为电子商务网站创建一个 CMS,用户可以在其中搜索产品标题、描述或 SKU,并且它将显示前 20 个结果。然后有一个“更多...”按钮,可加载接下来的 20 个产品。但是,我无法让“更多...”的查询输出相同数量的结果。这是我的模型中的 2 个函数:
public function searchProducts($searchText)
{
$this->db->select("prod_id, prod_sku, prod_title, prod_desc, prod_main_image");
$this->db->where("prod_sku LIKE '%{$searchText}%'");
$this->db->or_where("prod_title LIKE '%{$searchText}%'");
$this->db->or_where("prod_desc LIKE '%{$searchText}%'");
$this->db->order_by("prod_id", "desc");
$query = $this->db->get("products", 20);
return $this->checkSalesProducts($query->result());
}
public function loadMoreSearchProducts($searchText, $id)
{
$this->db->select("prod_id, prod_sku, prod_title, prod_desc, prod_main_image");
$this->db->where("(prod_sku LIKE '%{$searchText}%' OR prod_title LIKE '%{$searchText}%' OR prod_desc LIKE '%{$searchText}%') AND `prod_id` < {$id}");
$this->db->order_by("prod_id", "desc");
$query = $this->db->get("products", 20);
return $this->checkSalesProducts($query->result());
}
在加载更多函数中,ajax 调用会发送最后显示的产品的 ID,以便我可以对产品 ID 使用降序排序来获取接下来 20 个具有较低 ID 的产品。
有什么想法吗?
最佳答案
你想要像这样的“分页”。首先只有一个功能。
public function searchProducts($searchText, $page = 0)
{
$this->db->select("prod_id, prod_sku, prod_title, prod_desc, prod_main_image")
->where("prod_sku LIKE '%{$searchText}%'")
->or_where("prod_title LIKE '%{$searchText}%'")
->or_where("prod_desc LIKE '%{$searchText}%'")
->order_by("prod_id", "desc")
->limit(20, $page*20);
$query = $this->db->get("products");
return $this->checkSalesProducts($query->result());
}
这样,您将在每个不同的页面上加载接下来的 20 个结果。 $page = 0
将默认为前 20 个结果,使您的函数通用且模块化。
关于php - “加载更多”sql 函数未加载正确的产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11361442/