隨著網路的普及和快速發展,新聞發佈網站成為了人們獲取新聞資訊的重要管道。而PHP作為一種強大的伺服器端程式語言,被廣泛應用於網站開發之中。本文將一步步教你如何用PHP開發一個新聞發佈網站。
<?php $db_host = 'localhost'; $db_username = 'root'; $db_password = 'password'; $db_name = 'news'; $conn = new mysqli($db_host, $db_username, $db_password, $db_name); if ($conn->connect_error) { die("数据库连接失败:" . $conn->connect_error); }
<?php include 'db_connect.php'; $category = $_GET['category']; $sql = "SELECT * FROM news_articles WHERE category='$category'"; $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo "<h3>" . $row['title'] . "</h3>"; echo "<p>" . $row['content'] . "</p>"; } } else { echo "暂无新闻"; } $conn->close();
<?php include 'db_connect.php'; $id = $_GET['id']; $sql = "SELECT * FROM news_articles WHERE id='$id'"; $result = $conn->query($sql); if ($result->num_rows > 0) { $row = $result->fetch_assoc(); echo "<h1>" . $row['title'] . "</h1>"; echo "<p>" . $row['content'] . "</p>"; } else { echo "新闻不存在"; } $conn->close();
<?php include 'db_connect.php'; $sql = "SELECT * FROM news_articles ORDER BY timestamp DESC"; $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo "<h3>" . $row['title'] . "</h3>"; echo "<p>" . $row['content'] . "</p>"; } } else { echo "暂无新闻"; } $conn->close();
<?php include 'db_connect.php'; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $category = $_POST['category']; $title = $_POST['title']; $content = $_POST['content']; $timestamp = date('Y-m-d H:i:s'); $sql = "INSERT INTO news_articles (category, title, content, timestamp) VALUES ('$category', '$title', '$content', '$timestamp')"; if ($conn->query($sql) === TRUE) { echo "发布成功"; } else { echo "发布失败:" . $conn->error; } } $conn->close(); ?> <form method="POST" action="admin.php"> <input type="text" name="category" placeholder="分类" required> <input type="text" name="title" placeholder="标题" required> <textarea name="content" placeholder="内容" required></textarea> <button type="submit">发布新闻</button> </form>
至此,我們已經完成了一個簡單的新聞發佈網站的開發。你可以根據實際需求進行進一步的最佳化和擴展,例如添加用戶認證、新聞編輯、評論等功能。希望這篇文章能夠幫助你快速入門PHP開發新聞發佈網站。
以上是一步步教你如何用PHP開發新聞發佈網站的詳細內容。更多資訊請關注PHP中文網其他相關文章!