How to use PHP to implement a simple news release system
With the popularity of the Internet, news release systems have become a common need. This article will introduce how to use the PHP programming language and MySQL database to build a simple news release system, and attach code examples.
First, we need to create a MySQL database to store news data. Create a database named "news" in MySQL and create a table named "news_articles" in the database. The table structure is as follows:
CREATE TABLE news_articles (
id INT AUTO_INCREMENT PRIMARY KEY ,
title VARCHAR(255) NOT NULL,
content TEXT,
author VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Next, we write a PHP script to handle the function of adding news. Create a file called "add_news.php" and add the following code in it:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$title = $_POST["title"]; $content = $_POST["content"]; $author = $_POST["author"]; // 连接到数据库 $conn = mysqli_connect("localhost", "root", "", "news"); if ($conn === false) { die("连接数据库失败:" . mysqli_connect_error()); } // 执行插入数据的SQL语句 $sql = "INSERT INTO news_articles (title, content, author) VALUES ('$title', '$content', '$author')"; if (mysqli_query($conn, $sql)) { echo "新闻添加成功!"; } else { echo "添加新闻失败:" . mysqli_error($conn); } // 关闭数据库连接 mysqli_close($conn);
}
?>
Now, we create a file called "news_form.html", And add the following code there:
Below , we write a PHP script to handle the function of displaying the news list. Create a file called "list_news.php" and add the following code in it:
// Connect to the database
$conn = mysqli_connect("localhost", " root", "", "news");
if ($conn === false) {
die("连接数据库失败:" . mysqli_connect_error());
}
// Execute the SQL statement to query the data
$ sql = "SELECT * FROM news_articles";
$result = mysqli_query($conn, $sql);
// Display news list
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) { echo "<h3>{$row['title']}</h3>"; echo "<p>{$row['content']}</p>"; echo "<p>作者:{$row['author']}</p>"; echo "<hr>"; }
} else {
echo "暂无新闻";
}
// Close the database connection
mysqli_close($conn);
?>
Finally, we create a file called "news_list.php" and add the following code in it:
Visited by "news_list.php" file can display the news list.
The above are the steps and code examples to implement a simple news release system using PHP. With this example, you can learn how to build a simple web application using PHP and MySQL. Of course, this is just a basic version and you can extend and improve it according to your actual needs. Hope this article helps you!
The above is the detailed content of How to implement a simple news release system using PHP. For more information, please follow other related articles on the PHP Chinese website!