search
HomeBackend DevelopmentPHP TutorialDetailed 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. 新闻内容表

Detailed explanation of operating MySQL database with PHP (4)

字段名 解释
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[&#39;page&#39;])){    $page = 1; //默认为第一页
    $startrow = 0;
}else{    $page = (int)$_GET[&#39;page&#39;];      
//当前页数
    $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=&#39;news_add.php&#39;"/></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[&#39;id&#39;]?></td>
        <td>
            <a target="_blank" href="news_content.php?id=<?php echo $arr[&#39;id&#39;]?>">
                <?php echo $arr[&#39;title&#39;]?>
            </a>        
        </td>
        <td><?php echo $arr[&#39;author&#39;]?></td>
        <td><?php echo $arr[&#39;source&#39;]?></td>
        <td><?php echo $arr[&#39;orderby&#39;]?></td>
        <td><?php echo $arr[&#39;hits&#39;]?></td>
        <td><?php echo date("Y-m-d H:i", $arr[&#39;addate&#39;])?></td>
        <td>
            <a href="news_edit.php?id=<?php echo $arr[&#39;id&#39;]?>">修改</a>
            <a href="javascript:void(0)" onClick="confirmDel(<?php echo $arr[&#39;id&#39;]?>)">删除</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=&#39;manage.php?page=$i&#39;>$i</a>  ";    
                    }
                }            ?>
        </td>
    </tr></table></body></html>

运行的效果

Detailed explanation of operating MySQL database with PHP (4)

3. 显示新闻内容 news_content.php

  点击新闻列表中某条新闻的标题,之后会跳转到该条新闻的详细内容页面(news_content.php)

<!--news_content.php-->
<?php
//**************************读取一条记录******************************
//包含连接数据库的文件
include "conn.php";
//获取地址栏传递过来的id值
$id = $_GET[&#39;id&#39;];
//构建更新点击率的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[&#39;title&#39;]?></title>
</head>

<body>
<table width="1000" cellpadding="5" align="center">
    <tr>
        <th><h2><?php echo $arr[&#39;title&#39;]?></h2></th>
    </tr>
    <tr>
        <td bgcolor="#ccc" align="center">
            作者:<?php echo $arr[&#39;author&#39;]?>    
            来源:<?php echo $arr[&#39;source&#39;]?>    
            点击率:<?php echo $arr[&#39;hits&#39;]?>次    
            发布时间:<?php echo date("Y-m-d H:i", $arr[&#39;addate&#39;])?>
        </td>
    </tr>
    <tr>
        <td><?php echo $arr[&#39;content&#39;]?></td>
    </tr>
</table>
</body>
</html>

运行效果

Detailed explanation of operating MySQL database with PHP (4)

4. 添加新闻

  在新闻列表页(manage.php)点击“添加新闻”,会跳转到“添加新闻”页面(news_add.php)。添加成功后,数据库中就添加了该条新增记录了,然后跳转到操作成功提示页面,5秒后,跳转到新闻列表页面(manage.php)。

添加新闻(news_add.php)

<!--news_add.php-->

<?php
//*****************************添加新闻********************************

//连接MySQL数据库
include "conn.php";

//判断表单是否提交
if(isset($_POST[&#39;ac&#39;]) && $_POST[&#39;ac&#39;]=="add"){

    //获取表单提交的数据
    $cat = $_POST[&#39;cat&#39;];
    $title = $_POST[&#39;title&#39;];
    $author = $_POST[&#39;author&#39;];
    $source = $_POST[&#39;source&#39;];
    $orderby = $_POST[&#39;orderby&#39;];
    $keywords = $_POST[&#39;keywords&#39;];
    $description = $_POST[&#39;description&#39;];
    $content = $_POST[&#39;content&#39;];
    $addate = time();

    //构建写入的SQL语句
    $sql = "INSERT INTO 007_news(cat,title,author,source,orderby,keywords,description,content,addate) VALUES($cat,&#39;$title&#39;,&#39;$author&#39;,&#39;$source&#39;,$orderby,&#39;$keywords&#39;,&#39;$description&#39;,&#39;$content&#39;,$addate)";

    //执行SQL语句
    if(mysql_query($sql)){

        //如果执行成功,则跳转到success.php页面
        $url = "manage.php";
        $message = urlencode("记录添加成功!");
        echo "<script>location.href=&#39;success.php?url=$url&message=$message&#39;</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(&#39;textarea[name="content"]&#39;, {
        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(&#39;textarea[name="content"]&#39;, {
        allowFileManager : true   //是否允许上传文件
    });
});
</script>
<textarea id="content" name="content" style="width:100%;height:300px; "></textarea>

运行效果

Detailed explanation of operating MySQL database with PHP (4)

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=&#39;success.php?url=$url&message=$message&#39;</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[&#39;ac&#39;]) && $_POST[&#39;ac&#39;]=="add"){

    //获取表单提交的数据
    $cat = $_POST[&#39;cat&#39;];
    $title = $_POST[&#39;title&#39;];
    $author = $_POST[&#39;author&#39;];
    $source = $_POST[&#39;source&#39;];
    $orderby = $_POST[&#39;orderby&#39;];
    $keywords = $_POST[&#39;keywords&#39;];
    $description = $_POST[&#39;description&#39;];
    $content = $_POST[&#39;content&#39;];

    //通过表单提交用POST方式,获得隐藏域提交过来的id值
    //这里不直接通过GET方式来获取id值,而是用隐藏域来获得id,安全性更高,而且地址栏的值可以改动
    $id = $_POST[&#39;id&#39;];  

    //构建要修改的SQL语句
    $sql = "UPDATE 007_news SET cat=$cat,title=&#39;$title&#39;,author=&#39;$author&#39;,source=&#39;$source&#39;,orderby=$orderby,keywords=&#39;$keywords&#39;,description=&#39;$description&#39;,content=&#39;$content&#39; WHERE id=$id";

    //执行SQL语句
    if(mysql_query($sql)){

        //如果执行成功,则跳转到success.php页面
        $url = "manage.php";
        $message = urlencode("记录修改成功!");
        echo "<script>location.href=&#39;success.php?url=$url&message=$message&#39;</script>";
        exit();
    }

}else{  //表单提交之前,应先显示数据库中的原始数据

    //获取地址栏传递的id值
    $id = $_GET[&#39;id&#39;];

    //构建查询的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(&#39;textarea[name="content"]&#39;, {
        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[&#39;cat&#39;]==1){echo &#39;selected=selected&#39;;}?> >公司新闻</option>
                <option value="2" <?php if($arr[&#39;cat&#39;]==2){echo &#39;selected=selected&#39;;}?> >行业新闻</option>
                <option value="3" <?php if($arr[&#39;cat&#39;]==3){echo &#39;selected=selected&#39;;}?> >疾病预防</option>
                <option value="4" <?php if($arr[&#39;cat&#39;]==4){echo &#39;selected=selected&#39;;}?> >帮助文档</option>
            </select>
        </td>
    </tr>
    <tr>
        <td align="right">新闻标题:</td>
        <td><input type="text" name="title" size="100" value="<?php echo $arr[&#39;title&#39;]?>"/></td>
    </tr>
    <tr>
        <td align="right">作者:</td>
        <td>
            <input type="text" name="author" value="<?php echo $arr[&#39;author&#39;]?>" size="10"/>
            来源:<input type="text" name="source" value="<?php echo $arr[&#39;source&#39;]?>" size="40"/>
            排序:<input type="text" name="orderby" maxlength="2" value="<?php echo $arr[&#39;orderby&#39;]?>"/>
        </td>
    </tr>
    <tr>
        <td align="right">关键字:</td>
        <td><input type="text" name="keywords" size="100" value="<?php echo $arr[&#39;keywords&#39;]?>"/></td>
    </tr>
    <tr>
        <td align="right">描述:</td>
        <td><input type="text" name="description" size="100" value="<?php echo $arr[&#39;desciption&#39;]?>"></td>
    </tr>
    <tr>
        <td align="right">内容:</td>
        <td><textarea name="content" style="width:100%;height:240px;"><?php echo $arr[&#39;content&#39;]?></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!

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
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

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 Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor