목차
관련 권장사항:
백엔드 개발 PHP 튜토리얼 thinkPHP 페이징 기능에 대한 자세한 그래픽 설명

thinkPHP 페이징 기능에 대한 자세한 그래픽 설명

May 23, 2018 am 09:29 AM
php thinkphp 상해

이 글은 thinkPHP의 페이징 기능을 주로 소개하고, thinkPHP의 관련 운영 기법을 분석하여 제품 모델을 기반으로 페이징 기능을 완전한 예시 형태로 구현한 내용입니다. 필요하신 분들은 참고하시기 바랍니다

이 예시는 기사에서는 thinkPHP의 페이징 기능을 설명합니다. 다음과 같이 참조용으로 모든 사람과 공유하십시오.

interface ServiceInterFace:

<?php
/**
 * InterFaceService
 * @author yhd
 */
namespace Red;
interface ServiceInterFace {
  /**
   * 实例化当前类
   */
  public static function getInstance();
}
로그인 후 복사

StaticService 정적 서비스 클래스:

<?php
/**
 * 静态服务类
 * StaticService
 * @author yhd
 */
namespace Red;
class StaticService{
  protected static $data;
  /**
   * 设置静态数据
   * @param string $key key
   * @param mixed $data data
   * @return mixed
   */
  public static function setData($key,$data){
    self::$data[$key] = $data;
    return self::$data[$key];
  }
  /**
   * 通过引用使用静态数据
   * @param string $key key
   * @return mixed
   */
  public static function & getData($key){
    if(!isset(self::$data[$key])){
      self::$data[$key] = null;
    }
    return self::$data[$key];
  }
  /**
   * 缓存实例化过的对象
   * @param string $name 类名
   * @return 对象
   */
  public static function getInstance($name){
    $key = &#39;service_@_&#39;.$name;
    $model = &self::getData($key);
    if($model === null){
      $model = new $name();
    }
    return $model;
  }
  /**
   * html转义过滤
   * @param mixed $input 输入
   * @return mixed
   */
  public static function htmlFilter($input){
    if(is_array($input)) {
      foreach($input as & $row) {
        $row = self::htmlFilter($row);
      }
    } else {
      if(!get_magic_quotes_gpc()) {
        $input = addslashes($input);
      }
      $input = htmlspecialchars($input);
    }
    return $input;
  }
}
로그인 후 복사

abstract AbProduct 추상 제품 관리 클래스:

<?php
/**
* 抽象商品管理类
* AbProduct.class.php
* @lastmodify 2015-8-17
* @author yhd
*/
namespace Red\Product;
abstract class AbProduct{
  public $errorNum;
  /*
  *返回错误信息
  *@param $errorNum 错误代码
  */
  public function GetStatus(){
    $errorNum = $this->errorNum;
    switch($errorNum){
        case 0:
            $data[&#39;status&#39;] = 0;
            $data[&#39;message&#39;] = &#39;收藏成功&#39;;
            break;
        case 1:
            $data[&#39;status&#39;] = 1;
            $data[&#39;message&#39;] = &#39;收藏失败&#39;;
            break;
        case 2:
            $data[&#39;status&#39;] = 2;
            $data[&#39;message&#39;] = &#39;已收藏&#39;;
            break;
        case 3:
            $data[&#39;status&#39;] = 3;
            $data[&#39;message&#39;] = &#39;未登陆&#39;;
            break;
        case 4:
            $data[&#39;status&#39;] = 4;
            $data[&#39;message&#39;] = &#39;缺少参数&#39;;
            break;
        default:
            $data[&#39;status&#39;] = 200;
            $data[&#39;message&#39;] = &#39;未知错误&#39;;
    }
    return $data;
  }
로그인 후 복사

멤버모델 회원 모델:

<?php
/**
* 会员模型
* MemberModel.class.php
* @copyright (C) 2014-2015 red
* @license http://www.red.com/
* @lastmodify 2015-8-17
* @author yhd
*/
namespace Red\Passport\Models;
use Think\Model;
use Red\ServiceInterFace;
use Red\StaticService;
class MemberModel extends Model implements ServiceInterFace{
  protected $userId;
  protected $error;
  protected function _initialize(){
    $this->userId = getUserInfo(0);
  }
   /**
   * 实例化本类
   * @return MemberModel
   */
  public static function getInstance() {
    return StaticService::getInstance(__CLASS__);
  }
   /**
   *  获取登录用户信息
   * @param string  $data 查询条件
   * @return array
   */
  public function getUser($data = &#39;&#39;) {
    if(empty($data)){
      return $this->where("id=".$this->userId)->find();
    }else{
      return $this->field($data)->where("id=".$this->userId)->find();
    }
  }
  /**
   * 修改用户信息
   * @param array $data
   * @param array $where 查询条件
   */
  public function editUserInfo($data, $where = &#39;&#39;) {
    if( $this->_before_check($data) === false ){
      return $this->error[&#39;msg&#39;];
    }
    if(!empty($where) && is_array($where)){
      $condition[ $where[0] ] = array(&#39;eq&#39;, $where[1]);
      return $this->where($condition)->save($data);
    }
    return $this->where("id=".$this->userId)->save($data);
  }
  /**
   * 获取用户信息
   * @param string $data 用户名
   * return array()
   */
  public function checkUserInfo($str, $field = &#39;&#39;){
    //注册类型
    $info = CheckType($str);
    $condition[$info] = array(&#39;eq&#39;,$str);
    if(!empty($field)){
      return $this->field($field)->where($condition)->find();
    }
    return $this->where($condition)->find();
  }
  /**
   * 获取用户信息
   * @param array $data 用户名
   * return array()
   */
  public function getAccount($data){
    //注册类型
    $info = CheckType($data);
    $condition[&#39;id&#39;] = array(&#39;eq&#39;,$this->userId);
    $condition[$info] = array(&#39;eq&#39;,$data);
    return $this->where($condition)->find();
  }
  /**
   * 修改用户密码
   * @param array $data[&#39;id&#39;]用户ID
   * @param $data[&#39;passWord&#39;]用户密码
   * return true or false
   */
  public function upUserPassById($data){
    $condition[&#39;id&#39;] = array(&#39;eq&#39;,$data[&#39;id&#39;]);
    $status = $this->where($condition)->save(array("password"=>md5($data[&#39;password&#39;])));
    if($status){
        return TRUE;
    }else {
        return FALSE;
    }
  }
  /**
   * 校验用户的账号或者密码是否正确
   * @param $data[&#39;username&#39;] 用户名
   * @param $data[&#39;password&#39;] 密码
   * return true or false
   */
  public function checkUserPasswd($data= array()){
      $type = CheckType($data[&#39;username&#39;]);
      $condition[$type] = array(&#39;eq&#39;,$data[&#39;username&#39;]);
      $condition[&#39;password&#39;] = array(&#39;eq&#39;,md5($data[&#39;password&#39;]));
       return $this->where($condition)->find();
  }
  /**
   * 网页登录校验token
   * @param token string
   * return bool
   */
  public function checkToken($token){
      return $this->autoCheckToken($token);
  }
  /**
   * 后台封号/解封
   * param int $user_id
   */
  public function changeStatus($data){
    if($this->save($data)){
      return true;
    }else{
      return false;
    }
  }
  protected function _before_check(&$data){
    if(isset($data[&#39;username&#39;]) && empty($data[&#39;username&#39;])){
      $this->error[&#39;msg&#39;] = &#39;请输入用户名&#39;;
      return false;
    }
    if(isset($data[&#39;nickname&#39;]) && empty($data[&#39;nickname&#39;])){
      $this->error[&#39;msg&#39;] = &#39;请输入昵称&#39;;
      return false;
    }
    if(isset($data[&#39;realname&#39;]) && empty($data[&#39;realname&#39;])){
      $this->error[&#39;msg&#39;] = &#39;请输入真名&#39;;
      return false;
    }
    if(isset($data[&#39;email&#39;]) && empty($data[&#39;email&#39;])){
      $this->error[&#39;msg&#39;] = &#39;请输入邮箱&#39;;
      return false;
    }
    if(isset($data[&#39;mobile&#39;]) && empty($data[&#39;mobile&#39;])){
      $this->error[&#39;msg&#39;] = &#39;请输入手机号码&#39;;
      return false;
    }
    if(isset($data[&#39;password&#39;]) && empty($data[&#39;password&#39;])){
      $this->error[&#39;msg&#39;] = &#39;请输入密码&#39;;
      return false;
    }
    if(isset($data[&#39;headimg&#39;]) && empty($data[&#39;headimg&#39;])){
      $this->error[&#39;msg&#39;] = &#39;请上传头像&#39;;
      return false;
    }
    return true;
  }
}
로그인 후 복사

ProductModel 제품 모델:

<?php
/**
* 商品模型
* ProductModel.class.php
* @lastmodify 2015-8-17
* @author yhd
*/
namespace Red\Product\Models;
use Think\Model;
use Red\ServiceInterFace;
use Red\StaticService;
class ProductModel extends Model implements ServiceInterFace{
  /**
   * 实例化本类
   * @return ProductModel
   */
  public static function getInstance() {
    return StaticService::getInstance(__CLASS__);
  }
  /**
   * 单个商品
   * @param string $id
   * @param integer $status 状态 1:有效 2:无效
   * @param integer $onsale 是否上架 1:是 2:否
   * @return array 一维数组
   */
  public function getProOne($id, $status = 1 , $onsale = 1){
    $condition[&#39;onsale&#39;] = array(&#39;eq&#39;, $onsale); //是否上架
    $condition[&#39;status&#39;] = array(&#39;eq&#39;, $status); //状态
    $condition[&#39;id&#39;] = array(&#39;eq&#39;,$id);
    return $this->where($condition)->find();
  }
  /**
   * 商品列表
   * @param string $limit 查询条数
   * @param array $data 查询条件
   * @return array 二维数组
   */
  public function getProList($data = &#39;&#39;){
    $condition[&#39;onsale&#39;] = array(&#39;eq&#39;, $data[&#39;onsale&#39;]); //是否上架
    $condition[&#39;status&#39;] = array(&#39;eq&#39;, $data[&#39;status&#39;]); //状态
    $condition[&#39;type&#39;] = array(&#39;eq&#39;, $data[&#39;type&#39;]);  //分类
    if(isset($data[&#39;limit&#39;]) && isset($data[&#39;order&#39;]) ){
      $return =$this->where($condition)->limit($data[&#39;limit&#39;])->order($data[&#39;order&#39;])->select();
    }else{
      $return =$this->where($condition)->select();
    }
    return $return;
  }
  /**
   * 添加商品
   * @param array $data
   * @return int
   */
  public function addProduct($data){
    return $this->add($data);
  }
  /**
   * 删除商品
   *
   */
  public function delProduct($id){
    $condition[&#39;id&#39;] = array(&#39;eq&#39;, $id);
    return $this->where($condition)->delete();
  }
  /**
   * 修改商品
   * @param string|int $id
   * @param array $data
   * @return
   */
  public function editProdcut($id, $data){
    $condition[&#39;id&#39;] = array(&#39;eq&#39;, $id);
    return $this->where($condition)->save($data);
  }
  public function getProductInfo($product){
    if(empty($product) || !isset($product[&#39;product_id&#39;])){
      return array();
    }
    $info = $this->getProOne($product[&#39;product_id&#39;]);
    $product[&#39;name&#39;] = $info[&#39;name&#39;];
    $product[&#39;store_id&#39;] = $info[&#39;store_id&#39;];
    $product[&#39;price&#39;] = $info[&#39;price&#39;];
    $product[&#39;m_price&#39;] = $info[&#39;m_price&#39;];
    return $product;
  }
}
로그인 후 복사

ProductManage 제품 관리 클래스:

<?php
  namespace User\Controller;
  use Red\Product\ProductManage;
  class FavoriteController extends AuthController {
  public function index($page=1){
    $limit=1;
    $list = ProductManage::getInstance()->getCollectList($page,$limit);
    $showpage = create_pager_html($list[&#39;total&#39;],$page,$limit);
    $this->assign(get_defined_vars());
    $this->display();
  }
  public function cancelCollect(){
    $ids = field(&#39;ids&#39;);
    $return = ProductManage::getInstance()->cancelProductCollect($ids);
    exit(json_encode($return));
  }
}
로그인 후 복사

functions.php 페이지 매김 기능:

<?php
/**
 * 分页
 * @param $total 总条数
 * @param $page 第几页
 * @param $perpage 每页条数
 * @param $url 链接地址
 * @param $maxpage 最大页码
 * @return string 最多页数
*/
function create_pager_html($total, $page = 1, $perpage = 20, $url = &#39;&#39;, $maxpage = null) {
  $totalcount = $total;
  if (empty($url) || !is_string($url)) {
    $url = array();
    foreach ($_GET as $k => $v) {
      if ($k != &#39;page&#39;) {
        $url[] = urlencode($k) . &#39;=&#39; . urlencode($v);
      }
    }
    $url[] = &#39;page={page}&#39;;
    $url = &#39;?&#39; . implode(&#39;&&#39;, $url);
  }
  if ($total <= $perpage)
    return &#39;&#39;;
  $total = ceil($total / $perpage);
  $pagecount = $total;
  $total = ($maxpage && $total > $maxpage) ? $maxpage : $total;
  $page = intval($page);
  if ($page < 1 || $page > $total)
    $page = 1;
    $pages = &#39;<p class="pages"><a href="&#39; . str_replace(&#39;{page}&#39;, $page - 1 <= 0 ? 1 : $page - 1, $url) . &#39;" rel="external nofollow" title="上一页" class="page_start">上一页</a>&#39;;
  if ($page > 4 && $page <= $total - 4) {
    $mini = $page - 3;
    $maxi = $page + 2;
  } elseif ($page <= 4) {
    $mini = 2;
    $maxi = $total - 2 < 7 ? $total - 2 : 7;
  } elseif ($page > $total - 4) {
    $mini = $total - 7 < 3 ? 2 : $total - 7;
    $maxi = $total - 2;
  }
  for ($i = 1; $i <= $total; $i++) {
    if ($i != $page) {
      $pages .= &#39;<a class="page-num" href="&#39; . str_replace(&#39;{page}&#39;, $i, $url) . &#39;" rel="external nofollow" >&#39; . $i . &#39;</a>&#39;;
    } else {
      $pages .= &#39;<span class="page_cur">&#39; . $i . &#39;</span>&#39;;
    }
    if ($maxi && $i >= $maxi) {
      $i = $total - 2;
      $maxi = 0;
    }
    if (($i == 2 or $total - 2 == $i) && $total > 10) {
      $pages .= &#39;&#39;;
    }
    if ($mini && $i >= 2) {
      $i = $mini;
      $mini = 0;
    }
  }
  $pages .= &#39;<a href="&#39; . str_replace(&#39;{page}&#39;, $page + 1 >= $total ? $total : $page + 1, $url) . &#39;" rel="external nofollow" title="下一页" class="page_next">下一页</a><span class="pageOp"><span class="sum">共&#39; . $totalcount .
      &#39;条 </span><input type="text" class="pages_inp" id="pageno" value="&#39; . $page . &#39;" onkeydown="if(event.keyCode==13 && this.value) {window.location.href=\&#39;&#39; . $url . &#39;\&#39;.replace(/\{page\}/, this.value);return false;}"><span class="page-sum">/ &#39; .
      $total . &#39;页 </span><input type="button" class="pages_btn" value="GO" onclick="if(document.getElementById(\&#39;pageno\&#39;).value>0)window.location.href=\&#39;&#39; . $url . &#39;\&#39;.replace(/\{page\}/, document.getElementById(\&#39;pageno\&#39;).value);"></span></p>&#39;;
  return $pages;
}
로그인 후 복사

관련 권장사항:

SQLite 기반으로 페이지 매김 기능을 구현하는 PHP 메소드

PHP+Ajax 새로 고침 없음 구현하는 메소드 페이지 매김 기능

thinkPHP 메소드로 다중 테이블 쿼리 및 페이지 매김 기능 구현

위 내용은 thinkPHP 페이징 기능에 대한 자세한 그래픽 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Dec 24, 2024 pm 04:42 PM

PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 Dec 20, 2024 am 11:31 AM

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

JWT (JSON Web Tokens) 및 PHP API의 사용 사례를 설명하십시오. JWT (JSON Web Tokens) 및 PHP API의 사용 사례를 설명하십시오. Apr 05, 2025 am 12:04 AM

JWT는 주로 신분증 인증 및 정보 교환을 위해 당사자간에 정보를 안전하게 전송하는 데 사용되는 JSON을 기반으로 한 개방형 표준입니다. 1. JWT는 헤더, 페이로드 및 서명의 세 부분으로 구성됩니다. 2. JWT의 작업 원칙에는 세 가지 단계가 포함됩니다. JWT 생성, JWT 확인 및 Parsing Payload. 3. PHP에서 인증에 JWT를 사용하면 JWT를 생성하고 확인할 수 있으며 사용자 역할 및 권한 정보가 고급 사용에 포함될 수 있습니다. 4. 일반적인 오류에는 서명 검증 실패, 토큰 만료 및 대형 페이로드가 포함됩니다. 디버깅 기술에는 디버깅 도구 및 로깅 사용이 포함됩니다. 5. 성능 최적화 및 모범 사례에는 적절한 시그니처 알고리즘 사용, 타당성 기간 설정 합리적,

PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? Feb 07, 2025 am 11:57 AM

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

문자열로 모음을 계산하는 PHP 프로그램 문자열로 모음을 계산하는 PHP 프로그램 Feb 07, 2025 pm 12:12 PM

문자열은 문자, 숫자 및 기호를 포함하여 일련의 문자입니다. 이 튜토리얼은 다른 방법을 사용하여 PHP의 주어진 문자열의 모음 수를 계산하는 방법을 배웁니다. 영어의 모음은 A, E, I, O, U이며 대문자 또는 소문자 일 수 있습니다. 모음이란 무엇입니까? 모음은 특정 발음을 나타내는 알파벳 문자입니다. 대문자와 소문자를 포함하여 영어에는 5 개의 모음이 있습니다. a, e, i, o, u 예 1 입력 : String = "Tutorialspoint" 출력 : 6 설명하다 문자열의 "Tutorialspoint"의 모음은 u, o, i, a, o, i입니다. 총 6 개의 위안이 있습니다

PHP에서 늦은 정적 결합을 설명하십시오 (정적 : :). PHP에서 늦은 정적 결합을 설명하십시오 (정적 : :). Apr 03, 2025 am 12:04 AM

정적 바인딩 (정적 : :)는 PHP에서 늦은 정적 바인딩 (LSB)을 구현하여 클래스를 정의하는 대신 정적 컨텍스트에서 호출 클래스를 참조 할 수 있습니다. 1) 구문 분석 프로세스는 런타임에 수행됩니다. 2) 상속 관계에서 통화 클래스를 찾아보십시오. 3) 성능 오버 헤드를 가져올 수 있습니다.

php magic 방법 (__construct, __destruct, __call, __get, __set 등)이란 무엇이며 사용 사례를 제공합니까? php magic 방법 (__construct, __destruct, __call, __get, __set 등)이란 무엇이며 사용 사례를 제공합니까? Apr 03, 2025 am 12:03 AM

PHP의 마법 방법은 무엇입니까? PHP의 마법 방법은 다음과 같습니다. 1. \ _ \ _ Construct, 객체를 초기화하는 데 사용됩니다. 2. \ _ \ _ 파괴, 자원을 정리하는 데 사용됩니다. 3. \ _ \ _ 호출, 존재하지 않는 메소드 호출을 처리하십시오. 4. \ _ \ _ get, 동적 속성 액세스를 구현하십시오. 5. \ _ \ _ Set, 동적 속성 설정을 구현하십시오. 이러한 방법은 특정 상황에서 자동으로 호출되어 코드 유연성과 효율성을 향상시킵니다.

ThinkPhp6 라우팅 : 중국어와 같은 특수 문자를 포함하는 URL 매개 변수를 완전히 얻는 방법은 무엇입니까? ThinkPhp6 라우팅 : 중국어와 같은 특수 문자를 포함하는 URL 매개 변수를 완전히 얻는 방법은 무엇입니까? Apr 01, 2025 pm 02:51 PM

ThinkPhp6 라우팅 매개 변수는 중국어 및 완전한 획득으로 처리됩니다. ThinkPhp6 프레임 워크에서 특수 문자 (예 : 중국어 및 구두점 마크)를 포함하는 URL 매개 변수는 종종 처리됩니다 ...

See all articles