php+mysql留言板小案例

1.连接数据库


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

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

2.向数据库写入内容

<meta charset="utf-8">

<html lang="en">
<head>head>

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

#连接数据库

$link = mysqli_connect('localhost','root','123','liuyanban');
$result = mysqli_query($link,'SELECT * FROM liuyan ');
?>

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

#通过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>

#向数据库写入用户输入的数据

$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)

你可能感兴趣的:(php+mysql)