PHP开发新闻管理系统之修改功... 登录

PHP开发新闻管理系统之修改功能的实现(下)

上节我们讲到通过在数据库中进行查询,并把代码展示出来,下面我们来继续讲解修改的功能,先回顾一下上节课的完整源码

<?php
    header("Content-type: text/html; charset=utf-8");//设置编码
    $con =@mysql_connect("localhost","root","root") or die("数据库连接失败");
    mysql_select_db('news') or die("指定的数据库不能打开");
    mysql_query("set names utf8");//设置数据库的字符集
    $id=$_GET['id'];
    $sql="select * from new where id=$id";
    $res = mysql_query($sql);
    $row = mysql_fetch_array($res);
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <style type="text/css">
    *{margin:0px;padding:0px;}
    body{background:#ccc;}
    .add{width:450px;height:280px;background:#eee;float:left;}
    .cont{width:500px;height:350px;margin-top:5px;margin-left:5px;}
    form{margin-left:10px;padding-top:30px;}
    .sub{width:100px;height:40px;border:1px solid #ccc;}
    .sub:hover{background:#f90}
    </style>
</head>
<body>
    <div class="add">
        <div class="cont">
            <form method="post" action="modify.php?id=<?php echo $id;?>">
                标题:<input type="text" name="title" value="<?php echo $row['title']?>"></br></br>
                内容:<textarea cols="50" rows="5" name="content"><?php echo $row['content']?></textarea></br></br>
                <input type="submit" value="修改" class="sub">
            </form>
        </div>
    </div>
</body>
</html>

如上代码,表单提交到  modify.php   这个文件 ,接下来我们看一下这个文件 

首先还是要连接数据库

 <?php
    header("Content-type: text/html; charset=utf-8");//设置编码
    $con =@mysql_connect("localhost","root","root") or die("数据库连接失败");
    mysql_select_db('news') or die("指定的数据库不能打开");
    mysql_query("set names utf8");//设置数据库的字符集

然后获取表单信息

 <?php 
    $id = $_GET['id'];
    $title = $_POST['title'];
    $content = $_POST['content'];
    $messtime = time();

注意:这里我们也需要获取 id  上一节课我们是获取 id  然后在数据库中进行查询,把信息查询出来,这里我们在修改的过程中是需要条件的,比如修改那条信息,这里我们使用id 将会很方便

接下来写修改语句

$sql = "update new set title='$title',content='$content',messtime='$messtime' where id='$id'";

$res = mysql_query($sql);

修改语句写完之后对其进行判断

    if($res){
        echo "<script>alert('修改成功');location.href='newlist.php';</script>";
    }else{
        echo "<script>alert('修改失败');history.go(-1);</script>";
    }

完整代码如下: 

<?php
	header("Content-type: text/html; charset=utf-8");//设置编码
	$con =@mysql_connect("localhost","root","root") or die("数据库连接失败");
	mysql_select_db('news') or die("指定的数据库不能打开");
	mysql_query("set names utf8");//设置数据库的字符集

	$id = $_GET['id'];
	$title = $_POST['title'];
	$content = $_POST['content'];
	$messtime = time();

	$sql = "update new set title='$title',content='$content',messtime='$messtime' where id='$id'";
	$res = mysql_query($sql);
	if($res){
		echo "<script>alert('修改成功');location.href='newlist.php';</script>";
	}else{
		echo "<script>alert('修改失败');history.go(-1);</script>";
	}
?>

这样我们一个简单功能的修改就完成了

下一节
提交 重置代码
章节 评论 笔记 课件
  • 取消 回复 发送
  • 取消 发布笔记 发送