資料表中有個欄位 media 紀錄了一篇文章的圖片檔案,格式為 JSON,如下
{"uploads/1/main_66ac8b95069b7.jpg": "uploads/1/thumb_66ac8b95069b7.jpg", "uploads/1/main_66ac8b951ebae.jpg": "uploads/1/thumb_66ac8b951ebae.jpg", "uploads/1/main_66ac8b9535c40.jpg": "uploads/1/thumb_66ac8b9535c40.jpg"}
uploads/1/main_66ac8b95069b7.jpg 為原圖路徑
uploads/1/thumb_66ac8b95069b7.jpg 為縮圖路徑
最後會將json轉為PHP陣列 $news['media']:
編輯文章時,想加入一個圖片管理功能,會將 $news 送至 smarty5 樣板,請用此陣列,搭配BootStrap5,做出橫向排列的縮圖
每張縮圖加上checkbox複選框,讓使用者勾選後,可以利用ajax的方式,刪掉勾選圖片的原圖及縮圖,並同時更新media欄位的json內容。
templates/images.tpl
:
{* 在您的Smarty模板中 *}
<div class="container mt-4">
<h2>圖片管理</h2>
<div class="row" id="imageGallery">
{foreach $news.media as $full => $thumb}
<div class="col-md-3 mb-3">
<div class="card">
<img src="{$thumb}" class="card-img-top" alt="縮圖">
<div class="card-body">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="{$full}" id="check_{$full|md5}">
<label class="form-check-label" for="check_{$full|md5}">
選擇刪除
</label>
</div>
</div>
</div>
</div>
{/foreach}
</div>
<button id="deleteSelected" class="btn btn-danger mt-3">刪除選中的圖片</button>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#deleteSelected').click(function() {
var selectedImages = [];
$('input[type="checkbox"]:checked').each(function() {
selectedImages.push($(this).val());
});
if (selectedImages.length > 0) {
$.ajax({
url: 'delete_images.php',
method: 'POST',
data: {
images: selectedImages,
news_id: {$news.id} // 假設新聞ID存儲在 $news.id 中
},
success: function(response) {
var result = JSON.parse(response);
if (result.success) {
alert('選中的圖片已成功刪除');
// 從頁面中移除被刪除的圖片
selectedImages.forEach(function(image) {
$('input[value="' + image + '"]').closest('.col-md-3').remove();
});
} else {
alert('刪除圖片時發生錯誤');
}
},
error: function() {
alert('發生錯誤,請稍後再試');
}
});
} else {
alert('請選擇要刪除的圖片');
}
});
});
</script>
delete_images.php
,並於最開頭的地方引入 header.php
,如此,才有 $pdo
資料庫物件可以用
<?php
require 'header.php';
function deleteImages(int $newsId, array $images): bool
{
global $pdo; // 假設您已經有了資料庫連接
try {
// 獲取當前的media JSON
$stmt = $pdo->prepare("SELECT media FROM school_news WHERE id = ?");
$stmt->execute([$newsId]);
$currentMedia = json_decode($stmt->fetchColumn(), true);
if (!$currentMedia) {
return false;
}
foreach ($images as $fullPath) {
if (isset($currentMedia[$fullPath])) {
$thumbPath = $currentMedia[$fullPath];
// 刪除檔案
@unlink($fullPath);
@unlink($thumbPath);
// 從陣列中移除
unset($currentMedia[$fullPath]);
}
}
// 更新資料庫
$stmt = $pdo->prepare("UPDATE school_news SET media = ? WHERE id = ?");
$stmt->execute([json_encode($currentMedia), $newsId]);
return true;
} catch (Exception $e) {
error_log($e->getMessage());
return false;
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['images']) && isset($_POST['news_id'])) {
$result = deleteImages((int) $_POST['news_id'], $_POST['images']);
echo json_encode(['success' => $result]);
}
templates/create.tpl
,在最後面</form>
之外(避免按鈕影響原有表單),將 templates/images.tpl
引入
<button type="submit" class="btn btn-primary">提交</button>
</form>
{if $id}
{include file="images.tpl"}
{/if}