PHP开发新闻管理系统之添加功能的实现
修改功能的实现,我们来看以下流程图

下面我们来看以下添加页的代码:news.php
<!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="addnews.php">
标题:<input type="text" name="title"></br></br>
内容:<textarea cols="50" rows="5" name="content"></textarea></br></br>
<input type="submit" value="添加" class="sub">
</form>
</div>
</div>
</body>
</html>如上代码可以看到,表单提交到addnews.php文件中
下面我们来看以下addnews.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");//设置数据库的字符集
然后获取表单信息:
$title = $_POST['title'];
$content = $_POST['content'];
$messtime = time();
在对数据库添加之前,我们先要判断一下,文本框的标题和内容是不是为空,如果为空,我们给出提示,代码如下:
if(empty($title)){
echo "<script>alert('请输入标题');history.go(-1);</script>";
}elseif(empty($content)){
echo "<script>alert('请输入内容');history.go(-1);</script>";
}
当内容不为空时,我们才可以往数据库添加内容,代码如下:
$sql = "insert into new (title,content,messtime) values('$title','$content','$messtime')";
$result =mysql_query($sql);
if($result){
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");//设置数据库的字符集
//添加操作
$title = $_POST['title'];
$content = $_POST['content'];
$messtime = time();
if(empty($title)){
echo "<script>alert('请输入标题');history.go(-1);</script>";
}elseif(empty($content)){
echo "<script>alert('请输入内容');history.go(-1);</script>";
}else{
$sql = "insert into new (title,content,messtime) values('$title','$content','$messtime')";
$result =mysql_query($sql);
if($result){
echo "<script>alert('添加文章成功');location.href='newlist.php'</script>";
}else{
echo "<script>alert('添加文章失败');history.go(-1);</script>";
}
}
?>
