How to use PHP to implement a simple online personal diary system, specific code examples are required
In modern society, personal diaries have become a way for many people to record their lives, thoughts and An important way of emotion. With the popularity of the Internet, more and more people choose to record their diaries in online diary systems for easy viewing and sharing at any time. This article will introduce step by step how to use PHP language to implement a simple online personal diary system and provide specific code examples.
Step 1: Create database table structure
First, we need to create a MySQL database and create a table named "diary" in it. The table structure is as follows:
CREATE TABLE diary
(
id
int(11) NOT NULL AUTO_INCREMENT,
title
varchar (255) NOT NULL,
content
text NOT NULL,
create_time
datetime NOT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Step 2: Create a diary list page
Create a file named "index.php" to display the list of personal diaries. The code example is as follows:
// Connect to the database
$servername = "localhost";
$username = "root";
$password = "123456" ;
$dbname = "your_database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Query diary data
$sql = "SELECT * FROM diary";
$result = $conn->query($sql);
// Display diary list
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) { echo "<h2>" . $row["title"] . "</h2>"; echo "<p>" . $row["content"] . "</p>"; }
} else {
echo "暂无日记";
}
$ conn->close();
?>
Step 3: Create an add diary page
Create a file named "add_diary.php" for adding new journal. The code example is as follows:
// Connect to the database
$servername = "localhost";
$username = "root";
$password = "123456" ;
$dbname = "your_database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$title = $_POST["title"]; $content = $_POST["content"]; $create_time = date("Y-m-d H:i:s"); // 插入日记数据 $sql = "INSERT INTO diary (title, content, create_time) VALUES ('$title', '$content', '$create_time')"; if ($conn->query($sql) === TRUE) { echo "日记添加成功"; } else { echo "Error: " . $sql . "<br>" . $conn->error; }
}
$conn->close();
?>