search
HomeBackend DevelopmentPHP Tutorial原理与示例:php+mysql+jquery 生成静态网页(含后台编辑功能)

从Web的工作原理来看,用户访问HTML所带来的服务器负载要远小于访问动态页面,因为在前者中,服务器只用把对应的html代码发送给客户端即可,而在后者中,服务器则需要根据访问条件进行一系列的计算,然后生成html代码,最后把运算结果代码发送给客户端。 所以,对于访问量较大的宣传式网站(比如新闻类),要尽可能地使用静态页面。

另一方面,我们不可能让网站编辑人员来一个一个地手工制作这些HTML,那样就是回到多年前的纯静态时代了。我们可以用动态语言来方便、快捷地生成这些静态网页。而且,目前这一技术已经十分成熟。本文仅以最简单的原理和案例着手,试图讲明白大致的方法和流程,不关心具体的细节(比如文本编辑器)。

原理步骤:

1、制作一个内容为空的html页面,作为模板。

2、当网站编辑人员通过后台添加一条记录时,将其内容添加到模板文件的相应的位置上,然后将其保存为特定位置的html文件

3、在数据库中记录下该文件的信息

4、在前台,读取数据库中的记录并显示

5、后台编辑,本质上是对html文件的增、删、改,顺带对数据库中的记录也进行如上操作。


目录结构:


数据库设计:

create database cms_php_html;

use cms_php_html;

CREATE TABLE IF NOT EXISTS `newslist` (
 
 `nID` int(11) NOT NULL AUTO_INCREMENT,
 
`nTitle` varchar(50) COLLATE utf8_bin NOT NULL,
 
`nURL` varchar(100) COLLATE utf8_bin NOT NULL,
 
 PRIMARY KEY (`nID`)

) ENGINE=InnoDB  DEFAULT CHARSET=utf8 ;


代码:

1、前台首页: index.html

			<meta charset="utf-8">		<title>NewsList</title>		<script src="js/jquery-1.8.2.min.js" type="text/javascript" charset="utf-8"></script>		<script src="js/query.js" type="text/javascript" charset="utf-8"></script>		<script>					$(function(){				$.ajax({					type:"get",					url:"admin/query.php",					dataType:"json",					success:function(data){						$("#newsList").html();						$.each(data, function(index,row) { 										$("#newsList").append("<li><a href='"+ row['nURL']+"'>"+row['nTitle']+"");									});							}				});							})		</script>				
admin

2、前台查询数据库页面:admin/query.php

<?phpmysql_connect ("localhost","root","root");mysql_query("set names utf8");mysql_select_db("cms_php_html");$myrs=mysql_query("select * from newsList order by nID");while($row=mysql_fetch_array($myrs)){	$temp[]=$row;}echo(json_encode($temp));?>

3、后台编辑首页:admin/admin_index.html

			<meta charset="utf-8">		<title>CMS后台</title>		<script src="../js/jquery-1.8.2.min.js" type="text/javascript" charset="utf-8"></script>		<script type="text/javascript" src="../js/new.js"></script>		<!--<script src="../js/query.js" type="text/javascript" charset="utf-8"></script>-->		<script src="../js/saveEdit.js" type="text/javascript" charset="utf-8"></script>		<script src="../js/delete.js" type="text/javascript" charset="utf-8"></script>				<div><a href="../index.html" target="_blank">前台查看</a></div>		
  • 添加
  • 标题:
  • 内容:
  •   
  • 修改
  • 文件:
  • 标题:
  • 内容:
  •      
News List

4、与新增记录、修改记录有关的js:js/new.js

$(function() {	//首先在表格正文列出已有记录	$.ajax({		type:"get",		url:"../admin/query.php",		dataType:"json",		success:function(data){			$("#newsList").html("");			$.each(data, function(index,row) { 					$("#newsList").append("
  • "+row['nTitle']+"
  • "); }); $("#newsList li").each(function(){ $(this).bind('click',{url:$(this).attr('title')},readNews) }) } }); //清空新增记录的文本框 $("#newClear").click(function(){ newTitle=$("#newTitle").val("") newContent=$("#newContent").val(""); }) //清空修改记录的文本框 $("#editClear").click(function(){ newTitle=$("#oldTitle").val("") newContent=$("#oldContent").val(""); $("#pageFile").html("") }) //提交新增记录内容 $("#newSubmit").click(function(){ if($("#newTitle").val()!="" && $("#newContent").val()!="") { $("#newSubmit").val('添加中..'); $("#newSubmit").attr("disabled","disabled"); newTitle=$("#newTitle").val() newContent=$("#newContent").val(); $.ajax({ type:"post", url:"../admin/new.php", data:{txtTitle:newTitle,txtContent:newContent}, dataType:'html', success:function(data){ alert(data); $("#newSubmit").removeAttr("disabled"); $("#newSubmit").val('添加'); $.ajax({ type:"get", url:"../admin/query.php", dataType:"json", success:function(data){ //新增成功后刷新下方已有记录列表 $("#newsList").html(""); $.each(data, function(index,row) { $("#newsList").append("
  • "+row['nTitle']+"  
  • "); }); $("#newsList li").each(function(){ $(this).bind('click',{url:$(this).attr('title')},readNews) }) } }); } }); } })})//点击记录列表中任一条,会在修改区域的文本框中显示该记录的原有内容function readNews(evt){// alert(evt.data.url); $.ajax({ type:"get", url:"../admin/read.php", dataType:'json', data:{htmlUrl:evt.data.url}, success:function(data){// alert('returned') $("#oldTitle").val(data[0]); $("#oldContent").val(data[1]) $("#pageFile").html(evt.data.url) } });}
    5、与修改记录有关的js:js/saveEdit.js

    $(function(){	$("#oldSubmit").click(function(){		if($("#pageFile").text()!="" && $("#oldTitle").val()!="" && $("#oldContent").val()!="")		{			$("#oldSubmit").val('修改中...');			fileURL=$("#pageFile").html();			$("#oldSubmit").attr("disabled","disabled");			newTitle=$("#oldTitle").val()			newContent=$("#oldContent").val();			$.ajax({				type:"post",				url:"../admin/saveEdit.php",				data:{url:fileURL,title:newTitle,content:newContent},				dataType:'html',				success:function(data){					$("#oldSubmit").removeAttr("disabled");					$("#oldSubmit").val('修改');						alert(data);										$.ajax({						type:"get",						url:"../admin/query.php",						dataType:"json",						success:function(data){							$("#newsList").html("");							$.each(data, function(index,row) { 											$("#newsList").append("
  • "+row['nTitle']+"  
  • "); }); $("#newsList li").each(function(){ $(this).bind('click',{url:$(this).attr('title')},readNews) }) } }); } }); } })})function readNews(evt){// alert(evt.data.url); $.ajax({ type:"get", url:"../admin/read.php", dataType:'json', data:{htmlUrl:evt.data.url}, success:function(data){// alert('returned') $("#oldTitle").val(data[0]); $("#oldContent").val(data[1]) $("#pageFile").html(evt.data.url) } });}6、与删除记录有关的js:js/delete.js

    $(function(){	$("#oldDelete").click(function(){		if(window.confirm('确定删除?')==true)		{			currentURL=$("#pageFile").text();			$.ajax({				type:"post",				url:"../admin/delete.php",				data:{curl:currentURL},				dataType:'html',				success:function(data){					alert(data);					$.ajax({						type:"get",						url:"../admin/query.php",						dataType:"json",						success:function(data){							$("#newsList").html("");							$.each(data, function(index,row) { 									$("#newsList").append("
  • "+row['nTitle']+"
  • "); }); $("#newsList li").each(function(){ $(this).bind('click',{url:$(this).attr('title')},readNews) }) } }); } }); } })})
    7、新增记录的php实现代码:admin/new.php

    <?php $title=$_POST['txtTitle'];$content=$_POST['txtContent'];$fopen=fopen("../template/t1.html", "r");$templateContent=fread($fopen, filesize("../template/t1.html"));fclose($fopen);$templateContent=str_replace("{TITLE}",$title,$templateContent);$templateContent=str_replace("{CONTENT}",$content,$templateContent);$htmlName="../html/".date("YmdHis").'.html';$fwrite=fopen($htmlName,"w");   fwrite($fwrite,$templateContent); mysql_connect('localhost','root','root');mysql_query("set names utf8");mysql_select_db('cms_php_html');$url="http://localhost/phpToHtml".substr($htmlName, 2);$insertSql="insert into newsList values(null,'".$title."','".$url."')";mysql_query($insertSql);echo json_encode("ok");?>

    8、修改现有记录的php实现代码:admin/saveEdit.php

    <?php $url=$_POST['url'];$title=$_POST['title'];$content=$_POST['content'];$oldContent=file_get_contents($url);$newContent=preg_replace("#<title>(.*?)#s", "<title>".$title."</title>", $oldContent);$newContent=preg_replace("#(.*?)#s", "".$content."", $newContent);preg_match("#http://localhost/phpToHtml/(.*?).html#s", $url,$m);$fwrite=fopen("../".$m[1].".html","w");fwrite($fwrite,$newContent); mysql_connect("localhost","root","root");mysql_query("set names utf8");mysql_select_db("cms_php_html");mysql_query("update newsList set nTitle='".$title."' where nURL='".$url."'");echo("ok");?>

    9、读取已有的某条记录的php实现代码:admin/read.php

    <?php $htmlURL=$_GET['htmlUrl'];$fcontents=file_get_contents($htmlURL);preg_match("#<title>(.*?)#s",$fcontents,$titleMatches);preg_match("#(.*?)#s",$fcontents,$contentMatches);$row[0]=$titleMatches[1];$row[1]=$contentMatches[1];echo(json_encode($row));?>

    10、删除某条记录的php实现代码:admin/delete.php

    <?php $url=$_POST['curl'];mysql_connect("localhost","root","root");mysql_query("set names utf8");mysql_select_db("cms_php_html");mysql_query("delete from newsList where nURL='".$url."'");echo("ok");?>

    11、模板文件:template/t1.html

    			<meta charset="utf-8">		<title>{TITLE}</title>				<a href="../index.html">返回列表页</a>		<div>{CONTENT}</div>	

    结果:

    前台:

    前台打开链接后:

    后台首页:


    添加记录:

    添加后:


    修改记录:


    删除记录:


    删除后的列表:


    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's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

    PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

    PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

    PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

    PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

    PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

    PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

    PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

    PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

    The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

    Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

    PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

    What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

    In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

    Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

    The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use