留言板功能的實現,主要就是經過編程語言對數據庫進行操做,簡單說也就是插入和查詢的實現。無論是什麼語言進行實現,道理都是同樣的。php
應學習須要,這裏用php世界上最美的語言來進行實現。html
主要步驟爲:mysql
- 鏈接數據庫。
一句話:$conn=mysqli_connect('localhost','root','root','test');
括號裏分別對應數據庫服務器地址、用戶名、密碼、所要操做的數據庫名稱。 - 獲取文本框中數據,寫入數據庫表中
這裏我把表單內容提交到了本頁面,判斷提交內容是否爲空,再將內容寫入到數據庫中。
$_SERVER['REQUEST_METHOD']能夠用來判斷表單的提交方式,這裏我簡單的寫,
直接對POST內容進行判斷了(isset($_POST['msg']))。
$sqlstr="insert into msg_board(username,msg) values('".$username."','".$_POST['msg']."')";
mysqli_query($conn,$sqlstr);sql - 顯示留言內容
這就是對數據庫表進行查詢了。而後將留言輸出到頁面。
//查詢數據庫表
$sqlstr="select * from msg_board";
$result=mysqli_query($conn,$sqlstr);
//判斷查詢內容是否爲空
if(mysqli_num_rows($result)){
//對查詢獲得的內容逐條進行顯示
while($row=mysqli_fetch_assoc($result)){
echo "
<div>
<p id='msg'><span id='username'>".$row['username']."</span>".$row['msg']."</p>
</div>
";
}
}數據庫
大體內容就是這些了,下面附上完整代碼供來參考編程
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>php_msg_board</title> 6 7 <style> 8 9 #username{ 10 margin: 0px 10px 0px 5px; 11 padding-right: 5px; 12 border-right: 2px solid darkgray; 13 } 14 #msg{ 15 border: 2px solid darkgray; 16 width: 300px; 17 padding: 5px; 18 } 19 </style> 20 </head> 21 <body> 22 23 24 25 <form action="msg.php" method="POST" > 26 27 <textarea name="msg"></textarea> 28 29 <input type="submit" value="submit"> 30 31 </form> 32 33 34 <?php 35 36 $username="root"; 37 38 $conn=mysqli_connect('localhost','root','root','test'); 39 40 mysqli_query($conn,"set names utf8"); 41 42 if($conn){ 43 if(isset($_POST['msg'])){ 44 $sqlstr="insert into msg_board(username,msg) values('".$username."','".$_POST['msg']."')"; 45 mysqli_query($conn,$sqlstr); 46 } 47 $sqlstr="select * from msg_board"; 48 $result=mysqli_query($conn,$sqlstr); 49 if(mysqli_num_rows($result)){ 50 while($row=mysqli_fetch_assoc($result)){ 51 echo " 52 <div> 53 <p id='msg'><span id='username'>".$row['username']."</span>".$row['msg']."</p> 54 </div> 55 "; 56 } 57 } 58 } 59 else{ 60 echo "mysql connect error!"; 61 } 62 ?> 63 64 </body> 65 </html>
但願對你們有所幫助。服務器
原創不易,尊重版權。轉載請註明出處:http://www.cnblogs.com/xsmile/編程語言