Detailed explanation of operating MySQL database with PHP (4)
新闻内容模块
所涉及的内容
1. 新闻内容表的设计
2. 新闻列表的分页(即每页显示固定条数的新闻)
3. 显示新闻的内容(点击“新闻标题”,跳转到新闻内容页面(news_content.php)显示新闻具体内容)
4. 新闻的添加(点击“添加新闻”按钮,跳转到新闻添加页面(news_add.php))
5. 新闻的删除(点击“删除”,跳转到新闻删除页面(news_del.php))
6. 新闻的修改(点击“修改”,跳转到新闻修改页面(news_edit.php))
1. 新闻内容表
字段名 | 解释 |
---|---|
cat | 分类 |
title | 标题 |
author | 作者 |
source | 来源 |
keywords | 网页关键字 |
description | 描述 |
orderby | 排序 |
content | 内容 |
hits | 点击率 |
addate | 发布时间 |
2. 显示新闻列表 manage.php
该页面实现
新闻列表的分页
包含功能
1.显示新闻的内容(news_content.php)
2.新闻的添加(news_add.php)
3.新闻的删除(news_del.php)
4.新闻的修改(news_edit.php)
分页原理
项 | 变量表示 | 解释 |
---|---|---|
总记录数 | $records | mysql_num_rows() |
每页显示显示页数 | $pagesize | 用户定义 |
总页数 | $pages | $records / $pagesize |
当前页 | $page | 用户选择 |
函数ps
mysql_num_rows() 函数返回结果集中行的数目。
分页的SQL语句
SELECT * FROM news LIMIT \$startrow,\$pagesize;
页数 | 表示 |
---|---|
第一页 $page=1 | LIMIT 0,10 |
第二页 $page=2 | LIMIT 10,10 |
第三页 $page=3 | LIMIT 20,10 |
…… | …… |
可以总结出
$startrow = ($page - 1) * $pagesize;
新闻列表页面(manage.php)
<!--manage.php--> <?php //包含连接MySQL的文件include "conn.php"; //分页的相关变量$pagesize = 5; //每页显示的新闻条数 //获取地址栏中传递的page参数,确定当前页,当前行(所有记录中的) if(empty($_GET['page'])){ $page = 1; //默认为第一页 $startrow = 0; }else{ $page = (int)$_GET['page']; //当前页数 $startrow = ($page-1)*$pagesize; //当前行数}//构建查询的SQL语句 $sql = "SELECT * FROM 007_news"; //执行SQL语句,返回的是所有记录的结果集$result = mysql_query($sql);//总记录数和总页数 $records = mysql_num_rows($result);$pages = ceil($records / $pagesize);//构建分页的SQL语句 $sql = "SELECT * FROM 007_news ORDER BY orderby ASC,id DESC LIMIT $startrow,$pagesize"; //执行SQL语句,返回的是结果集(10条记录)$result = mysql_query($sql);?> <!DOCTYPE html> <html xmlns=" <head><meta charset=UTF-8> <title>管理新闻列表</title> <script type="text/javascript"> function confirmDel(id){ //询问是否删除记录 if(window.confirm("你确定要删除吗?")){ //跳转到PHP的删除页面 del.php location.href = "news_del.php?id="+id; } } </script> </head> <body> <p style="padding:5px;"> <input type="button" value="添加新闻" onClick="javascript:location.href='news_add.php'"/></p> <table width="70%" border="1" bordercolor="#CCC" rules="all" cellpadding="5" align="center"> <tr> <th>编号</th> <th>新闻标题</th> <th>作者</th> <th>来源</th> <th>排序</th> <th>点击率</th> <th>发布时间</th> <th>操作选项</th> </tr> <?php while($arr = mysql_fetch_assoc($result)){ ?> <tr> <td><?php echo $arr['id']?></td> <td> <a target="_blank" href="news_content.php?id=<?php echo $arr['id']?>"> <?php echo $arr['title']?> </a> </td> <td><?php echo $arr['author']?></td> <td><?php echo $arr['source']?></td> <td><?php echo $arr['orderby']?></td> <td><?php echo $arr['hits']?></td> <td><?php echo date("Y-m-d H:i", $arr['addate'])?></td> <td> <a href="news_edit.php?id=<?php echo $arr['id']?>">修改</a> <a href="javascript:void(0)" onClick="confirmDel(<?php echo $arr['id']?>)">删除</a> </td> </tr> <?php }?> <tr> <td colspan="8" align="center"> <?php $prev = $page-3; $next = $page+3; if($page < 4){ $prev = 1; $next = 7; //后面补齐 } if($page > $pages-3){ $next = $pages; $prev = $pages-6; //前面补齐 } for($i=$prev;$i<=$next;$i++){ //当前页页码号在中间,前后各3个页码号,显示7个页码号 if($i == $page){//当前页,不加链接 echo "$i "; }else{ echo "<a href='manage.php?page=$i'>$i</a> "; } } ?> </td> </tr></table></body></html>
运行的效果
3. 显示新闻内容 news_content.php
点击新闻列表中某条新闻的标题,之后会跳转到该条新闻的详细内容页面(news_content.php)
<!--news_content.php--> <?php //**************************读取一条记录****************************** //包含连接数据库的文件 include "conn.php"; //获取地址栏传递过来的id值 $id = $_GET['id']; //构建更新点击率的SQL语句 $sql = "UPDATE 007_news SET hits=hits+1 WHERE id=$id"; mysql_query($sql); //构建查询的SQL语句 $sql = "SELECT * FROM 007_news WHERE id=$id"; //执行SQL语句 $result = mysql_query($sql); //取出唯一的一条记录 $arr = mysql_fetch_assoc($result); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title><?php echo $arr['title']?></title> </head> <body> <table width="1000" cellpadding="5" align="center"> <tr> <th><h2><?php echo $arr['title']?></h2></th> </tr> <tr> <td bgcolor="#ccc" align="center"> 作者:<?php echo $arr['author']?> 来源:<?php echo $arr['source']?> 点击率:<?php echo $arr['hits']?>次 发布时间:<?php echo date("Y-m-d H:i", $arr['addate'])?> </td> </tr> <tr> <td><?php echo $arr['content']?></td> </tr> </table> </body> </html>
运行效果
4. 添加新闻
在新闻列表页(manage.php)点击“添加新闻”,会跳转到“添加新闻”页面(news_add.php)。添加成功后,数据库中就添加了该条新增记录了,然后跳转到操作成功提示页面,5秒后,跳转到新闻列表页面(manage.php)。
添加新闻(news_add.php)
<!--news_add.php--> <?php //*****************************添加新闻******************************** //连接MySQL数据库 include "conn.php"; //判断表单是否提交 if(isset($_POST['ac']) && $_POST['ac']=="add"){ //获取表单提交的数据 $cat = $_POST['cat']; $title = $_POST['title']; $author = $_POST['author']; $source = $_POST['source']; $orderby = $_POST['orderby']; $keywords = $_POST['keywords']; $description = $_POST['description']; $content = $_POST['content']; $addate = time(); //构建写入的SQL语句 $sql = "INSERT INTO 007_news(cat,title,author,source,orderby,keywords,description,content,addate) VALUES($cat,'$title','$author','$source',$orderby,'$keywords','$description','$content',$addate)"; //执行SQL语句 if(mysql_query($sql)){ //如果执行成功,则跳转到success.php页面 $url = "manage.php"; $message = urlencode("记录添加成功!"); echo "<script>location.href='success.php?url=$url&message=$message'</script>"; exit(); } } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>添加新闻</title> <!--引入编辑器文件和语言包--> <script charset="utf-8" src="js/editor/kindeditor-min.js"></script> <script charset="utf-8" src="js/editor/lang/zh_CN.js"></script> <script> //加入在线编辑器 var editor; KindEditor.ready(function(K) { //在当前网页中,查找<textarea name = "content"></textarea>,并替换成kindeditor编辑器。 editor = K.create('textarea[name="content"]', { allowFileManager : true //是否允许上传文件 }); }); </script> </head> <body> <form name="form1" method="post" action=""> <table width="800" border="1" rules="all" bordercolor="#ccc" cellpadding="5" align="center"> <tr> <th colspan="2">添加新闻</th> </tr> <tr> <td width="80" align="center">新闻类型:</td> <td> <select name="cat"> <option value="1">新闻类型1</option> <option value="2">新闻类型2</option> <option value="3">新闻类型3</option> <option value="4">新闻类型4</option> </select> </td> </tr> <tr> <td align="right">新闻标题:</td> <td><input type="text" name="title" size="100"/></td> </tr> <tr> <td align="right">作者:</td> <td> <input type="text" name="author" value="admin" size="10"/> 来源:<input type="text" name="source" value="default" size="40"/> 排序:<input type="text" name="orderby" maxlength="2" value="50"/> </td> </tr> <tr> <td align="right">关键字:</td> <td><input type="text" name="keywords" size="100"/></td> </tr> <tr> <td align="right">描述:</td> <td><input type="text" name="description" size="100"></td> </tr> <tr> <td align="right">内容:</td> <td><textarea name="content" style="width:100%;height:240px;"></textarea></td> </tr> <tr> <td> </td> <td> <input type="submit" value="提交"/> <input type="hidden" name="ac" value="add"/> <!--隐藏域,表单验证--> <input type="reset" value="重置"/> </td> </tr> </table> </form> </body> </html>
代码PS
上述代码中引入了在线HTML编辑器:kindeditor 将editor文件直接“复制”到要引入文件的同级目录即可。
在需要的编辑器的页面,引入如下文件:
<!--在代码中引入在线HTML编辑器:kindeditor--> <script charset="utf-8" src="js/editor/kindeditor-min.js"></script> <script charset="utf-8" src="js/editor/lang/zh_CN.js"></script> <script> //加入在线编辑器 var editor; KindEditor.ready(function(K) { //在当前网页中,查找<textarea name = ‘content’></textarea>,并替换成kindeditor编辑器。 editor = K.create('textarea[name="content"]', { allowFileManager : true //是否允许上传文件 }); }); </script> <textarea id="content" name="content" style="width:100%;height:300px; "></textarea>
运行效果
5. 删除新闻
在新闻列表页(manage.php)点击“删除”,出现确认删除的提示框,点击“确认”后,会跳转到新闻删除页面(news_del.php),对该条新闻进行删除,此后数据库中就没有该条记录了。删除成功后,跳转到操作成功提示页面,5秒后,跳转到新闻列表页面(manage.php)。
删除新闻(news_del.php)
<!--news_del.php--> <?php //**********************删除记录*********************** //包含连MySQL接数据库的文件conn.php include "conn.php"; //获取地址栏传递的id参数,GET方式获取地址栏数据,POST获取表单数据 $id = (int)$_GET["id"]; //构建删除的SQL语句 $sql = "DELETE FROM 007_news WHERE id=$id"; //执行SQL语句 if(mysql_query($sql)) { //如果执行成功,则跳转到success.php页面 $url = "manage.php"; $message = urlencode("id={$id}记录删除成功!"); echo "<script>location.href='success.php?url=$url&message=$message'</script>"; }else { //如果执行失败,则跳转到error.php页面 $message = urlencode("记录删除失败!"); header("location:error.php?message=$message"); } ?>
6. 修改新闻
在新闻列表页(manage.php)点击修改,会跳转到新闻修改页面(news_edit.php),首先页面会读取指定id的数据,并写入对应的表单输入框中,对照原始信息作修改,点击修改后,数据库的记录也就更新了。修改成功后,跳转到操作成功提示页面,5秒后,跳转到新闻列表页面(manage.php)。
修改新闻(news_edit.php)
<!--news_edit.php--> <?php //*****************************修改新闻******************************** //连接MySQL数据库 include "conn.php"; //判断表单是否提交 if(isset($_POST['ac']) && $_POST['ac']=="add"){ //获取表单提交的数据 $cat = $_POST['cat']; $title = $_POST['title']; $author = $_POST['author']; $source = $_POST['source']; $orderby = $_POST['orderby']; $keywords = $_POST['keywords']; $description = $_POST['description']; $content = $_POST['content']; //通过表单提交用POST方式,获得隐藏域提交过来的id值 //这里不直接通过GET方式来获取id值,而是用隐藏域来获得id,安全性更高,而且地址栏的值可以改动 $id = $_POST['id']; //构建要修改的SQL语句 $sql = "UPDATE 007_news SET cat=$cat,title='$title',author='$author',source='$source',orderby=$orderby,keywords='$keywords',description='$description',content='$content' WHERE id=$id"; //执行SQL语句 if(mysql_query($sql)){ //如果执行成功,则跳转到success.php页面 $url = "manage.php"; $message = urlencode("记录修改成功!"); echo "<script>location.href='success.php?url=$url&message=$message'</script>"; exit(); } }else{ //表单提交之前,应先显示数据库中的原始数据 //获取地址栏传递的id值 $id = $_GET['id']; //构建查询的SQL语句 $sql = "SELECT * FROM 007_news WHERE id=$id"; //执行SQL语句 $result = mysql_query($sql); //取出记录 $arr = mysql_fetch_assoc($result); } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>修改新闻</title> <!--引入编辑器文件和语言包--> <script charset="utf-8" src="js/editor/kindeditor-min.js"></script> <script charset="utf-8" src="js/editor/lang/zh_CN.js"></script> <script> //加入在线编辑器 var editor; KindEditor.ready(function(K) { //在当前网页中,查找<textarea name = "content"></textarea>,并替换成kindeditor编辑器。 editor = K.create('textarea[name="content"]', { allowFileManager : true //是否允许上传文件 }); }); </script> </head> <body> <form name="form1" method="post" action=""> <table width="800" border="1" rules="all" bordercolor="#ccc" cellpadding="5" align="center"> <tr> <th colspan="2">修改新闻</th> </tr> <tr> <td width="80" align="center">新闻类型:</td> <td> <select name="cat"> <option value="1" <?php if($arr['cat']==1){echo 'selected=selected';}?> >公司新闻</option> <option value="2" <?php if($arr['cat']==2){echo 'selected=selected';}?> >行业新闻</option> <option value="3" <?php if($arr['cat']==3){echo 'selected=selected';}?> >疾病预防</option> <option value="4" <?php if($arr['cat']==4){echo 'selected=selected';}?> >帮助文档</option> </select> </td> </tr> <tr> <td align="right">新闻标题:</td> <td><input type="text" name="title" size="100" value="<?php echo $arr['title']?>"/></td> </tr> <tr> <td align="right">作者:</td> <td> <input type="text" name="author" value="<?php echo $arr['author']?>" size="10"/> 来源:<input type="text" name="source" value="<?php echo $arr['source']?>" size="40"/> 排序:<input type="text" name="orderby" maxlength="2" value="<?php echo $arr['orderby']?>"/> </td> </tr> <tr> <td align="right">关键字:</td> <td><input type="text" name="keywords" size="100" value="<?php echo $arr['keywords']?>"/></td> </tr> <tr> <td align="right">描述:</td> <td><input type="text" name="description" size="100" value="<?php echo $arr['desciption']?>"></td> </tr> <tr> <td align="right">内容:</td> <td><textarea name="content" style="width:100%;height:240px;"><?php echo $arr['content']?></textarea></td> </tr> <tr> <td> </td> <td> <input type="submit" value="修改"/> <input type="hidden" name="ac" value="add"/> <!--隐藏域,表单验证--> <input type="hidden" name="id" value="<?php echo $id?>"/> <!--隐藏域,用于传递通过GET方式获得的id值--> <input type="reset" value="重置"/> </td> </tr> </table> </form> </body> </html>
The above is the detailed content of Detailed explanation of operating MySQL database with PHP (4). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
