search
HomeBackend DevelopmentPHP Tutorial前天因为项目需求开始学的PHP,写了个分页控件,拿出来请大神指教

前天开始学习PHP额,之前都用.NET的,新项目需求没办法,硬着头皮开始学了,写了个分页控件的东东,贴出来大神们指点指点,至于怎么调用,就不用我说了吧。。。

<?phpclass PageView{	public $showurl="pageindex";			/**	 * 返回生成好的分页HTML	 * @param int 表示分页控件要显示的索引页码数	 * @param int 表示 每页显示多条数据	 * @param int 表示总数据条数	 * @param int 表示当前是第几页用于hover样式显示	 */	function page_view($indexDisplay,$pageSize,$ItemCount,$pageIndex)	{		$pageview="<div class='pagecontrols'>";		if(intval($indexDisplay)<=0)$indexDisplay=0;		if(intval($pageSize)<=0)$pageSize=20;		if(intval($ItemCount)<=0)$ItemCount=0;		if(intval($pageIndex)<=0)$pageIndex=0;		//计算出总共有多少页		$pageCount=$ItemCount%$pageSize==0?$ItemCount/$pageSize:(int)($ItemCount/$pageSize)+1;		if($indexDisplay>$pageCount) $indexDisplay=$pageCount;		if($indexDisplay<=0)		{			$pageview=$pageview."   					    <span>首页</span> <span>上一页</span>				        <span>下一页</span> <span>尾页</span>				   </div>";		}		else		{			//生成好url并且要兼容含有其他参数列表的url			$url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."?";//不带参数的url地址			$urlparams=$_SERVER['QUERY_STRING'];//URL地址的参数列表,这里需要把它转换成一个array			$url=$url.$this->SplitStrForArray($urlparams).$this->showurl."=";//这里得到的url是除了pageindex之外的完整url可以用在分页的href上			if($pageIndex<=0)//假如选取的是第一页,则首页和上一页变灰色			{				$pageview="<div class='pagecontrols'>					<span>首页</span> <span>上一页</span>	";			}			else			{				$beforeIndex=$pageIndex-1;				$beforeUrl=$url.$beforeIndex;				$pageview=$pageview."<div class='pagecontrols'>					 <a href='".$url."0'>首页</a>					 <a href='".$beforeUrl."'>上一页</a>		";			}			for($i=0;$i<$indexDisplay;$i++)			{			   //加一个判断当前选区的页数获取焦点hobver			   if($i==$pageIndex)			   {			     $pageview=$pageview."			     		<a href='".$url.$i."' class='selecthover'>".($i+1)."</a>";			   }			   else			   {			   	 $pageview=$pageview."			     		<a href='".$url.$i."'>".($i+1)."</a>";			   }			}			if($pageIndex==$pageCount-1)//假如选取的是第一页,则首页和上一页变灰色			{				$pageview=$pageview."					<span>下一页</span> <span>尾页</span>					 </div>";			}			else 			{				$nextIndex=$pageIndex+1;				$nextHref=$url.$nextIndex;				$lastIndex=$pageCount-1;				$lastHref=$url.$lastIndex;				$pageview=$pageview."					 <a href='".$nextHref."'>下一页</a>					 <a href='".$lastHref."'>尾页</a>				 	</div>";			}		}					return $pageview;	}		/**	 * 处理url,把属于分页的pageindex=参数去掉,并返回	 * @param string 原字符串	 */	function SplitStrForArray($sourceStr)	{		if($sourceStr=="") return "";		$strarry= explode("&",$sourceStr);		$newstr="";		foreach($strarry as $key){			if(explode("=", $key)[0] !=$this->showurl)			{				$newstr=$newstr.$key."&";			}		}		/*if($newstr!="")		{			$newstr= substr($newstr, 0,strlen($newstr)-1);		}*/		return $newstr;	}}?>


回复讨论(解决方案)

恩很不错了。加油!

php 提供了
parse_str 用于将 url 参数串转换为数组
http_build_query  由于从数组创建 url 参数串

php 提供有
$_REQUEST 数组,不必再从 $_SERVER['QUERY_STRING'] 串转换

删去 pageindex 也只需
unset($_REQUEST['pageindex']);
然后
$url = http_build_query($_REQUEST);
即可

谢谢楼上所有人,很多不了解,走了些弯路,你们提出的,我会查找资料认真学习的。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools