PHP開發(fā) 發(fā)表評論功能教程之資料庫搭建
我們需要將我們發(fā)表的意見提交到資料庫保存起來,在即時提交到頁面上去
#下面我們建立一個名為'comments'的資料庫
#程式碼如下
<?php //建立'comments'數據庫 header("Content-type:text/html;charset=utf-8"); //設置編碼 $servername = "localhost"; $username = "root"; $password = "root"; // 創(chuàng)建連接 $conn = mysqli_connect($servername, $username, $password); mysqli_set_charset($conn,'utf8'); //設定字符集 // 檢測連接 if (!$conn) { die("連接失敗: " . mysqli_connect_error()); } // 創(chuàng)建數據庫 $sql = "CREATE DATABASE comments"; if (mysqli_query($conn, $sql)) { echo "數據庫創(chuàng)建成功"; } else { echo "數據庫創(chuàng)建失敗: " . mysqli_error($conn); } mysqli_close($conn); ?>
我們在建立一張名為'comments'的資料表
#id | user | comment | addtime | |
欄位類型 | int | varchar | varchar | #datetime? |
11 | 30 | #200 | ||
id | 評論人的暱稱 | 評論內容 | 評論的時間 |
<?php header("Content-type:text/html;charset=utf-8"); //設置編碼 $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "comments"; // 創(chuàng)建連接 $conn = mysqli_connect($servername, $username, $password, $dbname); mysqli_set_charset($conn,'utf8'); //設定字符集 // 檢測連接 if (!$conn) { die("連接失敗: " . mysqli_connect_error()); } // 使用 sql 創(chuàng)建數據表 $sql = "CREATE TABLE `comments` ( `id` int(11) NOT NULL auto_increment, `user` varchar(30) NOT NULL, `comment` varchar(200) NOT NULL, `addtime` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM; " ; if (mysqli_query($conn, $sql)) { echo "數據表 comments 創(chuàng)建成功"; } else { echo "創(chuàng)建數據表錯誤: " . mysqli_error($conn); } mysqli_close($conn); ?>下面建立我們的主頁?index.html 檔案