php+mysql簡單留言,適合新手


<html>
<head>
<title>
php留言板
</title>
<style>
p,textarea{vertical-align:top;}
</style>
</head>

<body>
<form action="submit.php" method="post">
<p>名字:<input type="text" name="username" /></p>
<p>留言:<textarea cols="30" rows="5" name="comment" /></textarea></p>
<input type="submit" value="提交"/>
</form>
<!--前端展示代碼-->
<?php  
$con=@mysql_connect('localhost','root','');
mysql_query('set names utf8');
mysql_select_db('guestbook',$con);
$sql='select * from comment';
$res=mysql_query($sql);
$array=array();
while($row=@mysql_fetch_array($res)){?>
   <b><?php echo $row['user'] ?></b>說:
   <p><?php echo $row['comment'] ?></p>
<?php
}
?>
</body>
</html>

下面是php腳本

<?php
$user = $_POST['username'];
$comment = $_POST['comment'];
print_r($_POST);
$con=@mysql_connect('localhost','root','');
mysql_query('set names utf8');
if(mysql_select_db('guestbook',$con)){
    $sql="insert into comment(user,comment) values('$user','$comment')";

    if(mysql_query($sql)){
        echo "數據插入成功";
        header("location:/index.php");
    }else{
        echo "寫入失敗";
    }

}
?>

數據表的結構

代碼要點

1.textarea可以設置大小,rows代表行數,cols代表列數
2.insert語句插入的列名不用引號,可能識別不出,反正我去掉引號就能插入了
$sql="insert into comment(user,comment) values('$user','$comment')";
3.mysql_query對select,show,explain,describe語句返回資源類型
對其他語句返回true or false,記住及時變換
4.php跳轉代碼 header("location:/index.php");
5.設置mysql字符集mysql_query('set names utf8');
6.mysql從select取出來的資源用mysql_fetch_array結合while遍歷
while($row=@mysql_fetch_array($res)){....函數體}

7.mysql經常報錯,是一些函數即將被棄用,看哪個報錯,在前面加上@符號屏蔽掉就可以了

 


免責聲明!

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



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