php+mysql留言板小案例

1.连接数据库

<?php
$link = mysqli_connect('localhost','数据库登录名','数据库登陆密码','要连接的数据库名称');  #连接数据库

$result = mysqli_query($link,'SELECT * FROM liuyan '); #获取数据库中liuyan表里的内容
?>

2.向数据库写入内容

<meta charset="utf-8">
<!DOCTYPE html>
<html lang="en">
<head></head>

#样式
<style>
    ul,li{list-style: none}
    .ly{text-align: center}
    .author{}
</style>   
<body>

#连接数据库
<?php
$link = mysqli_connect('localhost','root','123','liuyanban');
$result = mysqli_query($link,'SELECT * FROM liuyan ');
?>

#将表里的内容遍历出来
<?php  while($row = mysqli_fetch_array($result)){  ?>
<ul class="ly">
    <div class="author"><?php echo $row['author'];  ?></div>
    <div class="time"><?php echo $row['time'];  ?></div>
    <div style="clear: both"><?php echo $row['content'];  ?></div>
    <hr>
</ul>
<?php  }?>

#通过post获取表单中的内容
<form style="text-align: center" method="post">
    <p>作者</p>
    <input type="text" name="author" >
    <p>内容</p>
    <textarea name="content"></textarea>
    <div></div>
    <input type="submit">
</form>

#向数据库写入用户输入的数据
<?php
$author = $_POST['author'];
$content = $_POST['content'];
$time =date("Y-m-d H:i:s");
$sql = "insert into liuyan values(null,'$author','$time','$content');";
if (mysqli_query($link,$sql)){
    echo "插入成功!";
}else{
    echo "失败!";
}
mysqli_close($link); #关闭数据库连接
?>
</body>
</html>

数据库名为liuyanban
liuyan表结构如下:

mysql> desc liuyan;
+---------+-------------+------+-----+---------+----------------+
| Field   | Type        | Null | Key | Default | Extra          |
+---------+-------------+------+-----+---------+----------------+
| id      | int(11)     | NO   | PRI | NULL    | auto_increment |
| author  | varchar(20) | YES  |     | NULL    |                |
| time    | varchar(20) | YES  |     | NULL    |                |
| content | text        | YES  |     | NULL    |                |
+---------+-------------+------+-----+---------+----------------+
4 rows in set (0.02 sec)

猜你喜欢

转载自blog.csdn.net/key_book/article/details/80341164