PHP開發 發表評論功能教學之PHP頁面

先來看PHP讀取和產生JSON資料的server.php程式碼。

0.jpg

#程式碼如下

<?php
header("Content-type:text/html;charset=utf-8");    //设置编码
$conn=mysqli_connect("localhost","root","root","comments");
mysqli_set_charset($conn,"utf8");
$sql="SELECT * from comments";
$que=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($que)){
      $comments[] = array("id"=>$row[id],"user"=>$row[user],"comment"=>$row[comment],"addtime"=>$row[addtime]);
}
echo json_encode($comments);
?>

注意:你的PHP版本應該是5.2以上才能使用json_encode函數。


comments.php 程式碼

#comment.php接收前台ajax提交過來的暱稱和評論內容參數,判斷參數的合法性,然後將資料插入資料庫中,如果成功,則輸出1,傳回前台jQuery處理。

<?php
header("Content-type:text/html;charset=utf-8");    //设置编码
$user = htmlspecialchars(trim($_POST['user']));
$txt = htmlspecialchars(trim($_POST['txt']));
$time = date("Y-m-d H:i:s");
if(empty($user)){
   echo "昵称不能为空!";
   exit;
}
if(empty($txt)){
   echo "评论内容不能为空!";
   exit;
}
$conn=mysqli_connect("localhost","root","root","comments");
mysqli_set_charset($conn,"utf8");
$sql="insert into comments(user,comment,addtime)values('$user','$txt','$time')";
$que=mysqli_query($conn,$sql);
if($que)  echo "1";
?>


#我們將我們的HTML頁面跟PHP程式碼組合起來,就能實現我們的註解功能了


本例使用簡單容易的程式碼詮釋了輕量、高效的jQuery結合PHP的ajax運作機制,當然這只是一個基礎的例子,jQuery還能做很多事情,留給大家去盡情發揮吧。


#
繼續學習
||
<?php header("Content-type:text/html;charset=utf-8"); //设置编码 $conn=mysqli_connect("localhost","root","root","comments"); mysqli_set_charset($conn,"utf8"); $sql="SELECT* from comments"; $que=mysqli_query($conn,$sql); while($row=mysqli_fetch_array($que)){ $comments[] = array("id"=>$row[id],"user"=>$row[user],"comment"=>$row[comment],"addtime"=>$row[addtime]); } echo json_encode($comments); ?>
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!