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经常报错,是一些函数即将被弃用,看哪个报错,在前面加上@符号屏蔽掉就可以了

原文地址:https://www.cnblogs.com/txxt/p/5635410.html