随着互联网的普及和快速发展,新闻发布网站成为了人们获取新闻资讯的重要渠道。而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中文网其他相关文章!