PHP Mysql如何实现数据库增删改查?

发布时间:2025-04-11 点击:11
php mysql实现数据库增删改查的方法:1、创建入口文件【index.html】连接数据库、查询数据;2、点击增加按钮,通过【addnews.html】添加数据;3、点击删除按钮,通过服务端文件【action-del.php】进行删除。
php mysql实现数据库增删改查的方法:
1. 查询数据库
1.1. 创建文件dbconfig.php,保存常量
<?php define("host","localhost"); define("user","root"); define("pass","");define("dbname","news");1.2. 创建入口文件index.html(连接数据库、查询数据)
<!doctype html><html><head><meta charset="utf-8"><title>新闻后台管理系统</title></head><style type="text/css">.wrapper {width: 1000px;margin: 20px auto;}h2 {text-align: center;}.add {margin-bottom: 20px;}.add a {text-decoration: none;color: #fff;background-color: green;padding: 6px;border-radius: 5px;}td {text-align: center;}</style><body><div><h2>新闻后台管理系统</h2><div><a href="addnews.html">增加新闻</a></div><table width="960" border="1"><tr><th>id</th><th>标题</th><th>关键字</th><th>作者</th><th>发布时间</th><th>内容</th><th>操作</th></tr><?php // 1.导入配置文件 require "dbconfig.php"; // 2. 连接mysql $link = @mysql_connect(host,user,pass) or die("提示:数据库连接失败!"); // 选择数据库 mysql_select_db(dbname,$link); // 编码设置 mysql_set_charset('utf8',$link);// 3. 从dbname中查询到news数据库,返回数据库结果集,并按照addtime降序排列 $sql = 'select * from news order by id asc'; // 结果集 $result = mysql_query($sql,$link); // var_dump($result);die;// 解析结果集,$row为新闻所有数据,$newsnum为新闻数目$newsnum=mysql_num_rows($result); for($i=0; $i<$newsnum; $i ){$row = mysql_fetch_assoc($result);echo "<tr>";echo "<td>{$row['id']}</td>";echo "<td>{$row['title']}</td>";echo "<td>{$row['keywords']}</td>";echo "<td>{$row['autor']}</td>";echo "<td>{$row['addtime']}</td>";echo "<td>{$row['content']}</td>";echo "<td><a href='javascript:del({$row['id']})'>删除</a><a href='editnews.php?id={$row['id']}'>修改</a> </td>";echo "</tr>";}// 5. 释放结果集mysql_free_result($result);mysql_close($link);?></table></div><script type="text/javascript">function del (id) {if (confirm("确定删除这条新闻吗?")){window.location = "action-del.php?id=" id;}}</script></body></html>页面如图:
2. 增加新闻
2.1 点击增加按钮,通过页面addnews.html添加数据
<!doctype html> <html> <head> <meta charset="utf-8"> <title>添加新闻</title> </head><style type="text/css">form{margin: 20px;}</style><body><form action="action-addnews.php" method="post"> <label>标题:</label><input type="text" name="title"> <label>关键字:</label><input type="text" name="keywords"> <label>作者:</label><input type="text" name="autor"> <label>发布时间:</label><input type="date" name="addtime"> <label>内容:</label><input type="text" name="content"> <input type="submit" value="提交"> </form> </body> </html>2.2 创建处理增加新闻的服务端文件action-addnews.php
<?php// 处理增加操作的页面 require "dbconfig.php";// 连接mysql$link = @mysql_connect(host,user,pass) or die("提示:数据库连接失败!");// 选择数据库mysql_select_db(dbname,$link);// 编码设置mysql_set_charset(&

兴宁SEO:网站SEO最大的几个优点
程序员买云服务器开发程序
甘肃内网ftp服务器租用云空间
ascii是什么意思?
白沙云服务器租用购买
电脑资源不足怎么解决?老司机告诉你电脑资源不足的解决方法
如新增域名备案的话是否可以绑定在在原有的服务器
客户那边打开是这样的我访问正常