PHP如何實(shí)現(xiàn)留言板功能
首先創(chuàng)建消息表,其主要字段有發(fā)送者的名稱,消息內(nèi)容,以及消息發(fā)送時(shí)間;
SQL:
CREATE TABLE `guanhui`.`message` ( `id` INT(10) NOT NULL AUTO_INCREMENT COMMENT '消息ID' , `sender` VARCHAR(60) NOT NULL COMMENT '發(fā)送者' , `content` TEXT NOT NULL COMMENT '消息內(nèi)容' , `send_time` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '發(fā)送時(shí)間' , PRIMARY KEY (`id`) ) ENGINE = MyISAM;
然后在前端創(chuàng)建表單并將留言消息查詢出來(lái),進(jìn)行列表展示;
表單HMTL:
<form action="./send_message.php" method="POST"> <input type="text" name="sender" placeholder="你的昵稱"> <textarea rows="4" name="content" placeholder="留言內(nèi)容"></textarea> <button type="submit">發(fā)送</button> </form>
展示列表:
<?php //鏈接數(shù)據(jù)庫(kù) $conn = mysql_connect("loclhost:3306","root","root"); //判斷錯(cuò)誤函數(shù) if(!$conn){ die(mysql_error()); } //選擇數(shù)據(jù)庫(kù) mysql_query("use message",$conn); //設(shè)定字符集編碼 mysql_query("set names utf8",$conn); //查詢語(yǔ)句 $sql = "select * from message"; //執(zhí)行語(yǔ)句 $res = mysql_query($sql); //建立一個(gè)空數(shù)組 $data = array(); //執(zhí)行循環(huán) while($row = mysql_fetch_assoc($res)){ $data[] = $row; } ?> <table> <tr> <th>ID</th> <th>Name</th> <th>Sender</th> <th class="content">Content</th> <th>操作</th> </tr> <?php foreach($data as $k=>$v){?> <tr> <td><?=$v['id']?></td> <td><?=$v['name']?></td> <td><?=$v['sender']?></td> <td><?=$v['content']?></td> <td> <a href="./update.php?id=<?=$v['id']?>">修改</a> <a href="./del.php?id=<?=$v['id']?>">刪除</a> </td> </tr> <?php }?> <table>
最后將表單提交過(guò)來(lái)的信息保存到數(shù)據(jù)庫(kù)即可。
<?php //鏈接數(shù)據(jù)庫(kù) $conn = mysql_connect("loclhost:3306","root","root"); //判斷錯(cuò)誤函數(shù) if(!$conn){ die(mysql_error()); } //選擇數(shù)據(jù)庫(kù) mysql_query("use message",$conn); //設(shè)定字符集編碼 mysql_query("set names utf8",$conn); //獲取表單值 $name = $_POST['name']; $sender = $_POST['sender']; $content =$_POST['content']; //插入數(shù)據(jù)庫(kù)語(yǔ)句 $sql = "insert into message(name,sender,content)values('$name','$sender','$content')"; //執(zhí)行數(shù)據(jù) $res = mysql_query($sql); //判斷結(jié)果 if($res){ echo "增加成功"; }else{ die("增加失敗".mysql_error()); }
推薦教程:《PHP教程》