Web Design Laboratory
請用php5.6寫一個新聞發佈程式,包含新聞輸入介面:有新聞主題、新聞內容輸入框及一個圖片上傳框。
另外寫一個新聞展示頁面,對應輸入的資料做排版顯示。
再幫我創建一個連結資料庫的程式,讓此新聞發佈系統完整。
接著我們來看看Gemini提供的數據 :
建議使用 MySQL 作為資料庫。
news 表:
id (INT, 主鍵)
title (VARCHAR)
content (TEXT)
image (VARCHAR)
created_at (TIMESTAMP)
新增新聞頁面 (add_news.php)
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 接收表單資料
$title = $_POST['title'];
$content = $_POST['content'];
$image = $_FILES['image']['name'];
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
// 資料庫連線
$servername = "your_servername";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("連線失敗: " . $conn->connect_error);
}
// 圖片上傳
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
// 插入資料庫
$sql = "INSERT INTO news (title, content, image, created_at) VALUES ('$title', '$content', '$image', NOW())";
if ($conn->query($sql) === TRUE) {
echo "新增成功";
} else {
echo "新增失敗: " . $conn->error;
}
$conn->close();
}
?>
<form method="post" enctype="multipart/form-data">
標題: <input type="text" name="title"><br>
內容: <textarea name="content"></textarea><br>
圖片: <input type="file" name="image"><br>
<input type="submit" value="新增">
</form><br><br></code></pre></div><br>
</p>
<p><span style="font-size: 26px; color: yellow;">以下語句顯示今天的日期</span><br>
<div style="background-color: #fff; width:100%;">
<?php
$today = date("d/m/Y");
echo $today;
?>
顯示新聞頁面 (news_list.php)
<?php
// 資料庫連線 (同上)
$servername = "your_servername";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
$sql = "SELECT * FROM news";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<h2>" . $row["title"] . "</h2>";
echo "<p>" . $row["content"] . "</p>";
echo "<img src='uploads/" . $row["image"] . "' alt='新聞圖片'>";
}
} else {
echo "沒有資料";
}
$conn->close();>