記錄一下我在學習《十天學會PHP》(第六版)的過程當中的遇到的重難點,該課程是學習製做一個簡單的留言板。php
<?php include('connect.php'); $sql = "SELECT * FROM msg ORDER BY id DESC"; $mysqli_result = $db->query($sql); if ($mysqli_result === false) { echo "SQL錯誤"; exit; } while ($row = $mysqli_result->fetch_array(MYSQL_ASSOC)) { $rows[] = $row; } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>留言本</title> <style> .wrap{ width: 600px; margin: 0px auto; } .add{ overflow: hidden; } .add .content{ width: 598px; margin: 0; padding: 0; } .add .user{ float: left; } .add .btn{ float: right; } .msg{ margin: 20px 0px; background: #ccc; padding: 5px; } .msg .info{ overflow: hidden; } .msg .user{ float: left; color: blue; } .msg .time{ float: right; color: #999; } .msg .content{ width: 100%; } </style> </head> <body> <div class="wrap"> <!-- 發表留言 --> <div class="add"> <form action="save.php" method="post"> <textarea name="content" class="content" cols="50" rows="5"></textarea> <input name="user" class="user" type="text" /> <input class="btn" type="submit" value="發表留言" /> </form> </div> <?php foreach ($rows as $row) { ?> <!-- 查看留言 --> <div class="msg"> <div class="info"> <span class="user"><?php echo $row['user'];?></span> <span class="time"><?php echo date("Y-m-d H:i:s", $row['intime']);?></span> </div> <div class="content"> <?php echo $row['content'];?> </div> </div> <?php } ?> </div> </body> </html>
<?php //預先定義數據庫連接參數 $host = '127.0.0.1'; $dbuser = 'root'; $password = '123456'; $dbname = 'php10'; $db = new mysqli($host, $dbuser, $password, $dbname); if ($db->connect_errno <> 0) { die('連接數據庫失敗'); } //設定數據庫數據傳輸䣌編碼 $db->query("SET NAME UTF8"); ?>
<?php class input{ function post($content) { if ($content == '') { return false; } //禁止使用的用戶名 $n = ['張三','李四','王五']; foreach ($n as $name) { if ($content == $name) { return false; } } return true; } } ?>
<?php include('input.php'); include('connect.php'); $content = $_POST['content']; $user = $_POST['user']; $input = new input(); //調用函數,檢查留言內容 $is = $input->post($content); if ($is == false) { die('留言內容的數據不正確'); } //調用函數,檢查留言人 $is = $input->post($user); if ($is == false) { die('留言人的數據不正確'); } //數據入庫 $time = time(); $sql = "INSERT INTO msg(content, user, intime) VALUES ('{$content}', '{$user}', '{$time}')"; $is = $db->query($sql); header("location: gbook.php"); ?>