首先創建訊息表,其主要欄位有發送者的名稱,訊息內容,以及訊息發送時間;

然后在前端創建表單并將留言訊息查詢出來,進行串列展示,index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <form action="./send_message.php" method="POST"> <input type="text" name="sender" placeholder="你的昵稱"><br> <textarea rows="5" cols="22" name="content" placeholder="留言內容"></textarea> <br> <button type="submit">發送</button> </form> <table id="list" border="1" cellspacing="0" style="margin-top:20px;"> <tr> <th>ID</th> <th>Name</th> <th>Sender</th> <th class="content">Content</th> <th>操作</th> </tr> <table> <script src="https://cdn.staticfile.org/jquery/3.5.1/jquery.js"></script> <script> $.get('/test/main.php',function(data){ data = JSON.parse(data).data; var html = ''; $(data).each(function(index,item){ html+= ` <tr> <td>${item.id}</td> <td>${item.sender}</td> <td>${item.content}</td> <td>${item.send_time}</td> <td> <a href="./update.php?id=${item.id}">修改</a> <a href="./del.php?id=${item.id}">洗掉</a> </td> </tr> `; }); $('#list').append(html); }); </script> </body> </html>
將表單提交過來的資訊保存到資料庫,send_message.php
<?php $send_time = time(); $sender = $_POST['sender']; $content = $_POST['content']; $con = mysqli_connect('localhost','root','123456'); if(!$con){ die('資料庫連接失敗').mysqli_error(); } mysqli_select_db($con,'test'); mysqli_query('set names utf8'); $sql = "insert into message(sender,content,send_time) values('$sender','$content','$send_time')"; $res = mysqli_query($con,$sql); if($res){ echo '<script>alert("留言成功");window.location.href="https://www.cnblogs.com/chenyingying0/p/index.html";</script>'; }else{ echo '<script>alert("留言失敗");window.location.href="https://www.cnblogs.com/chenyingying0/p/index.html";</script>'; }
從資料庫讀取資料,并回傳json,main.php
<?php $con = mysqli_connect('localhost','root','123456'); if(!$con){ die('資料庫連接失敗').mysqli_error(); } mysqli_select_db($con,'test'); mysqli_query('set names utf8'); $sql = 'select * from message'; $res = mysqli_query($con,$sql); $arr = []; while($row = mysqli_fetch_array($res,MYSQLI_ASSOC)){ $row['send_time'] = date('Y-m-d H:i:s',$row['send_time']); $arr[] = $row; } if(isset($res)){ echo json_encode(array( 'code'=>0, 'msg'=>'ok', 'data'=>$arr )); }else{ echo json_encode(array( 'code'=>0, 'msg'=>'聊天資訊為空' )); } ?>
效果如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/30820.html
標籤:PHP
上一篇:PHP中實作頁面跳轉的方式(php跳轉,js跳轉,html跳轉)
下一篇:php如何去除空陣列
