PHP开发简单新闻发布系统之新闻发布页PHP代码
这一节我们通过后台的PHP代码来实现添加数据到数据库并展示在新闻列表页
主要思路:
在表单中填写新闻的内容,包括:标题title, 作者author, 内容content ,另外的字段id, 发布时间created_at, 修改时间updated_at的内容有服务器完成,当然也要自己写程序,只是不由自己手动而已。提交表单后,用 MySQL 语句将它们添加到数据库中。
实例中会使用发布时间created_at, 修改时间updated_at,我们将它们直接设置当前的发布时间和修改时间。
就要使用 date()这个函数:把时间戳格式化为更易读的日期和时间。
可以获取简单的日期和时间
date("Y-m-d")表示获取年-月-日
date(" H:i:s")表示获取小时-分钟--秒数
因为我们都使用东半球时区,在这里我们使用date_default_timezone_set('Asia/Shanghai'),设置时区为上海所在时区。

当然首先我们还是需要连接数据库,这里创建了一个名为test的数据库。
<?php
$link = mysqli_connect('localhost','username','password','test');
if (!$link) {
die("连接失败:".mysqli_connect_error());
}
?>我们使用POST方式来获取数据
<?php
$title = isset($_POST['title'])?$_POST['title']:""; //标题
$author = isset($_POST['author'])?$_POST['author']:""; //作者
$content = isset($_POST['content'])?$_POST['content']:""; //新闻内容
$created_at = date("Y-m-d H:i:s"); //发布时间
$updated_at = date("Y-m-d H:i:s"); //修改时间
?>使用 insert into():向数据库表(创建一个名为new的表)中添加数据 ,
<?php
$sql="insert into new(title,author,content,created_at,updated_at) values('$title','$author','$content','$created_at','$updated_at')";
$rel = mysqli_query($link,$sql); //执行sql语句
?>展示完整代码publish.php文件 :
<?php
header("content-type:text/html;charset=utf8");
date_default_timezone_set('Asia/Shanghai');
//连接数据库
$link = mysqli_connect('localhost','username','password','test');
if (!$link) {
die("连接失败:".mysqli_connect_error());
}
$title = isset($_POST['title'])?$_POST['title']:"";
$author = isset($_POST['author'])?$_POST['author']:"";
$content = isset($_POST['content'])?$_POST['content']:"";
$created_at = date("Y-m-d H:i:s");
$updated_at = date("Y-m-d H:i:s");
//执行插入语句
$sql="insert into new(title,author,content,created_at,updated_at) values('$title','$author','$content','$created_at','$updated_at')";
$rel = mysqli_query($link,$sql);
//执行sql语句
if($rel){
echo "<script>alert('新闻发布成功');window.location.href='list.php'</script>"; //发布成功跳转到新闻列表页list.php
}else{
echo "<script>alert('新闻发布失败');window.location.href='publish.php'</script>";
}
?>

苏打水
我的为什么是发布失败
8年前 添加回复 1