php留言板的實現


留言板功能的實現,主要就是通過編程語言對數據庫進行操作,簡單說也就是插入和查詢的實現。不管是什么語言進行實現,道理都是一樣的。

應學習需要,這里用php世界上最美的語言來進行實現。

主要步驟為:

  1. 連接數據庫。
    一句話:$conn=mysqli_connect('localhost','root','root','test');
    括號里分別對應數據庫服務器地址、用戶名、密碼、所要操作的數據庫名稱。

  2. 獲取文本框中數據,寫入數據庫表中
    這里我把表單內容提交到了本頁面,判斷提交內容是否為空,再將內容寫入到數據庫中。
    $_SERVER['REQUEST_METHOD']可以用來判斷表單的提交方式,這里我簡單的寫,
    直接對POST內容進行判斷了(isset($_POST['msg']))。

    $sqlstr="insert into msg_board(username,msg) values('".$username."','".$_POST['msg']."')";
    mysqli_query($conn,$sqlstr);

  3. 顯示留言內容
    這就是對數據庫表進行查詢了。然后將留言輸出到頁面。

    //查詢數據庫表
    $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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM