PHP develops simple guestbook adding message function
This section introduces the function of adding messages in a simple guestbook
The main thing is to add content in the text box, click submit, and then the user information and messages are displayed on the message page. information. And add this information to the database.
First we need to judge the <input> text box and <textarea> content box
or use jquery
Set the id first
昵稱:<input type="text" name="nickname" id="nickname"/> 留言:<textarea name="message" id="message"></textarea>
Then judge by the character length
<script type="text/javascript"> function validate_input(){ var l=$("#nickname").val().trim().length; if(l==0) {alert("昵稱不能為空");return false;}; if(l>6) {alert("昵稱要6個(gè)字符以內(nèi)");return false;} l=$("#message").val().trim().length; if(l==0) {alert("留言內(nèi)容不能為空");return false;} if(l>300) {alert("留言內(nèi)容要300字符以內(nèi)");return false;} return true; } </script>
trim() function removes blank characters or other predefined characters on both sides of the string.
When adding a message, we are also adding data to the database. We need to connect to the database first and then use SQL statements to add data.
Here is a class LyDB that uses the database for our convenience.
<?php class LyDB{ var $_host="localhost"; var $_user="username"; var $_password="password"; var $_database="test"; var $link; public function __construct(){ //設(shè)置公共函數(shù) date_default_timezone_set('PRC'); $this->link = mysqli_connect($this->_host,$this->_user,$this->_password,$this->_database); //連接數(shù)據(jù)庫 if (!$this->link) { die('Could not connect to MySQL: ' . mysqli_connect_error()); //判斷是否連接 } } public function __destruct(){ mysqli_close($this->link); } public function insert($nickname,$avatar,$message) { $message=str_replace ("<" , "<" , $message); //str_replace() 函數(shù)以其他字符替換字符串中的一些字符(區(qū)分大小寫)。 $message=str_replace (">" , ">" , $message); $message=str_replace ("\n" , " " , $message); $message=trim($message); //trim() 函數(shù)移除字符串兩側(cè)的空白字符或其他預(yù)定義字符。 $lytime=date("Y-m-d H:i:s"); $sql="insert into ly (nickname,message,avatar,lytime)values('$nickname','$message','$avatar','$lytime')"; $query=mysqli_query($this->link,$sql); if($query){ return true; } else { return false; } } } ?>
str_replace() function replaces some characters in the string with other characters (case sensitive)