基于PHP+MySQL实现后台公告点击按钮同步至网站首页
Hey there! Let's get your announcement sync and display feature up and running smoothly. I'll walk you through each step with practical code snippets that fit your PHP + phpMyAdmin setup.
First things first—we need a place to store the announcement. Head to phpMyAdmin, select your database, and run this SQL to create an announcements table (tweak field names if needed):
CREATE TABLE announcements ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, content TEXT NOT NULL, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP );
This table tracks the announcement title, content, and automatically updates the timestamp whenever you edit it. Since you probably only need one active announcement at a time, we'll just use the first row (or update the same row every time).
Your admin page needs two parts: a form to edit the announcement, and code to save it to the database when the "Sync to Homepage" button is clicked.
Here's the full Admin Page Code (admin_announcement.php):
<?php // Database connection (replace with your own credentials) $servername = "localhost"; $username = "your_db_user"; $password = "your_db_pass"; $dbname = "your_db_name"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Handle form submission (when sync button is clicked) if ($_SERVER["REQUEST_METHOD"] == "POST") { $title = $_POST['announcement_title']; $content = $_POST['announcement_content']; // Check if an announcement already exists (update if yes, insert if no) $check_query = "SELECT id FROM announcements LIMIT 1"; $result = $conn->query($check_query); if ($result->num_rows > 0) { // Update existing announcement $sql = "UPDATE announcements SET title = ?, content = ? WHERE id = 1"; } else { // Insert new announcement $sql = "INSERT INTO announcements (title, content) VALUES (?, ?)"; } // Use prepared statement to prevent SQL injection $stmt = $conn->prepare($sql); $stmt->bind_param("ss", $title, $content); if ($stmt->execute()) { $success_msg = "Announcement synced to homepage successfully!"; } else { $error_msg = "Error: " . $stmt->error; } $stmt->close(); } // Fetch current announcement to pre-fill the form $current_announcement = []; $fetch_query = "SELECT title, content FROM announcements LIMIT 1"; $result = $conn->query($fetch_query); if ($result->num_rows > 0) { $current_announcement = $result->fetch_assoc(); } $conn->close(); ?> <!DOCTYPE html> <html> <head> <title>Admin - Edit Announcement</title> <!-- Add your admin page CSS here to match your screenshot's layout --> </head> <body> <h1>Edit Site Announcement</h1> <?php if (isset($success_msg)) echo "<p style='color:green;'>$success_msg</p>"; ?> <?php if (isset($error_msg)) echo "<p style='color:red;'>$error_msg</p>"; ?> <form method="POST" action=""> <label for="announcement_title">Title:</label><br> <input type="text" id="announcement_title" name="announcement_title" value="<?php echo isset($current_announcement['title']) ? htmlspecialchars($current_announcement['title']) : ''; ?>" required><br><br> <label for="announcement_content">Content:</label><br> <textarea id="announcement_content" name="announcement_content" rows="8" cols="50" required><?php echo isset($current_announcement['content']) ? htmlspecialchars($current_announcement['content']) : ''; ?></textarea><br><br> <button type="submit">Sync to Homepage</button> </form> </body> </html>
Just swap in your database credentials, then adjust the HTML/CSS to match your existing admin page layout (based on your screenshot).
Now we need to pull the latest announcement from the database and show it on your homepage. Add this code to your homepage's relevant display section:
<?php // Database connection (same credentials as admin page) $servername = "localhost"; $username = "your_db_user"; $password = "your_db_pass"; $dbname = "your_db_name"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Fetch the latest announcement (grab the first/only one) $sql = "SELECT title, content, updated_at FROM announcements LIMIT 1"; $result = $conn->query($sql); if ($result->num_rows > 0) { $announcement = $result->fetch_assoc(); echo "<div class='announcement-section'>"; echo "<h2>" . htmlspecialchars($announcement['title']) . "</h2>"; echo "<p>" . nl2br(htmlspecialchars($announcement['content'])) . "</p>"; echo "<small>Last updated: " . date('F j, Y, g:i a', strtotime($announcement['updated_at'])) . "</small>"; echo "</div>"; } else { // Default message if no announcement exists echo "<div class='announcement-section'>"; echo "<p>No active announcement at this time.</p>"; echo "</div>"; } $conn->close(); ?>
Style the .announcement-section with CSS to match your homepage's design (align it with your screenshot's display area).
- Security: Always use prepared statements (like in the code above) to block SQL injection. Never plug user input directly into SQL queries.
- HTML Escaping:
htmlspecialchars()prevents XSS attacks when outputting user-generated content—don't skip this! - Credentials: For production, store database credentials in a separate config file outside your web root instead of hardcoding them.
- Error Handling: Replace
die()statements with user-friendly messages or logging for live sites.
That's all! When you edit the announcement in the admin page and click "Sync to Homepage", the database updates instantly, and the homepage will load the new content on its next refresh.
内容的提问来源于stack exchange,提问作者Prince

