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'),設定時區為上海所在時區。

1605.png

當然首先我們還是需要連接資料庫,這裡建立了一個名為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>";
 }
?>


#
繼續學習
||
<?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>"; } ?>
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!