功能齊全的映像庫,具有使用 PHP、HTML、jQuery、AJAX、JSON、Bootstrap、CSS 和 MySQL 上傳功能。該專案包含詳細的分步解決方案以及程式碼解釋和文檔,使其成為一個全面的學習教程。
主題:php、mysql、部落格、ajax、bootstrap、jquery、css、圖片庫、檔案上傳
逐步解決方案
1. 目錄結構
simple-image-gallery/ │ ├── index.html ├── db/ │ └── database.sql ├── src/ │ ├── fetch-image.php │ └── upload.php ├── include/ │ ├── config.sample.php │ └── db.php ├── assets/ │ ├── css/ │ │ └── style.css │ ├── js/ │ │ └── script.js │ └── uploads/ │ │ └── (uploaded images will be stored here) ├── README.md └── .gitignore
2. 資料庫架構
db/database.sql:
CREATE TABLE IF NOT EXISTS `images` ( `id` int(11) NOT NULL AUTO_INCREMENT, `file_name` varchar(255) NOT NULL, `uploaded_on` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3. 設定檔
設定設定(include/config.sample.php)
<?php define('DB_HOST', 'localhost'); // Database host define('DB_NAME', 'image_gallery'); // Database name define('DB_USER', 'root'); // Change if necessary define('DB_PASS', ''); // Change if necessary define('UPLOAD_DIRECTORY', '/assets/uploads/'); // Change if necessary ?>
4. 設定資料庫連線
建立資料庫連線(include/db.php)
<?php include 'config.php'; // Database configuration $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]; // Create a new PDO instance try { $pdo = new PDO($dsn, DB_USER, DB_PASS, $options); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set error mode to exception } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); // Display error message if connection fails } ?>
5. HTML 和 PHP 結構
HTML 結構 (index.html)
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image Gallery Upload</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/css/styles.css"> <div class="container"> <h1 id="Image-Gallery">Image Gallery</h1> <div class="row"> <div class="col-md-6 offset-md-3"> <form id="uploadImage" enctype="multipart/form-data"> <div class="form-group"> <label for="image">Choose Image</label> <input type="file" name="image" id="image" class="form-control" required> </div> <button type="submit" class="btn btn-primary">Upload</button> </form> <div id="upload-status"></div> </div> </div> <hr> <div class="row" id="gallery"> <!-- Images will be loaded here --> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="assets/js/script.js"></script> <!-- Custom JS -->
6. JavaScript 和 AJAX
AJAX 處理 (assets/js/script.js)
$(document).ready(function(){ // load gallery on page load loadGallery(); // Form submission for image upload $('#uploadImage').on('submit', function(e){ e.preventDefault(); // Prevent default form submission var file_data = $('#image').prop('files')[0]; var form_data = new FormData(); form_data.append('file', file_data); //hide upload section $('#uploadImage').hide(); $.ajax({ url: 'src/upload.php', // PHP script to process upload type: 'POST', dataType: 'text', // what to expect back from the server cache: false, data: new FormData(this), // Form data for upload processData: false, contentType: false, success: function(response){ let jsonData = JSON.parse(response); if(jsonData.status == 1){ $('#image').val(''); // Clear the file input loadGallery(); // Fetch and display updated images $('#upload-status').html('<div class="alert alert-success">'+jsonData.message+'</div>'); } else { $('#upload-status').html('<div class="alert alert-success">'+jsonData.message+'</div>'); // Display error message } // hide message box autoHide('#upload-status'); //show upload section autoShow('#uploadImage'); } }); }); }); // Function to load the gallery from server function loadGallery() { $.ajax({ url: 'src/fetch-images.php', // PHP script to fetch images type: 'GET', success: function(response){ let jsonData = JSON.parse(response); $('#gallery').html(''); // Clear previous images if(jsonData.status == 1){ $.each(jsonData.data, function(index, image){ $('#gallery').append('<div class="col-md-3"><img class="img-responsive img-thumbnail lazy" src="/static/imghwm/default1.png" data-src="assets/uploads/'+image.file_name+'" alt="PHP 速成課程:簡單圖片庫" ></div>'); // Display each image }); } else { $('#gallery').html('<p>No images found...</p>'); // No images found message } } }); } //Auto Hide Div function autoHide(idORClass) { setTimeout(function () { $(idORClass).fadeOut('fast'); }, 1000); } //Auto Show Element function autoShow(idORClass) { setTimeout(function () { $(idORClass).fadeIn('fast'); }, 1000); }
7. 後端 PHP 腳本
取得影像 (src/fetch-images.php)
<?php include '../include/db.php'; // Include database configuration $response = array('status' => 0, 'message' => 'No images found.'); // Fetching images from the database $query = $pdo->prepare("SELECT * FROM images ORDER BY uploaded_on DESC"); $query->execute(); $images = $query->fetchAll(PDO::FETCH_ASSOC); if(count($images) > 0){ $response['status'] = 1; $response['data'] = $images; // Returning images data } // Return response echo json_encode($response); ?> ?>
圖片上傳 (src/upload.php)
<?php include '../include/db.php'; // Include database configuration $response = array('status' => 0, 'message' => 'Form submission failed, please try again.'); if(isset($_FILES['image']['name'])){ // Directory where files will be uploaded $targetDir = UPLOAD_DIRECTORY; $fileName = date('Ymd').'-'.str_replace(' ', '-', basename($_FILES['image']['name'])); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); // Allowed file types $allowTypes = array('jpg','png','jpeg','gif'); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES['image']['tmp_name'], $targetFilePath)){ // Insert file name into database $insert = $pdo->prepare("INSERT INTO images (file_name, uploaded_on) VALUES (:file_name, NOW())"); $insert->bindParam(':file_name', $fileName); $insert->execute(); if($insert){ $response['status'] = 1; $response['message'] = 'Image uploaded successfully!'; }else{ $response['message'] = 'Image upload failed, please try again.'; } }else{ $response['message'] = 'Sorry, there was an error uploading your file.'; } }else{ $response['message'] = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; } } // Return response echo json_encode($response); ?>
6.CSS樣式
CSS 樣式 (assets/css/style.css)
body { background-color: #f8f9fa; } #gallery .col-md-4 { margin-bottom: 20px; } #gallery img { display: block; width: 200px; height: auto; margin: 10px; }
文件和評論
- config.php:包含資料庫配置並使用PDO連接到MySQL。
- index.php:具有 HTML 結構的主頁,包括用於樣式設定的 Bootstrap 以及用於新增/編輯貼文的模式。
- assets/js/script.js: 處理載入和儲存貼文的 AJAX 請求。使用 jQuery 進行 DOM 運算和 AJAX。
- src/fetch-images.php: 從資料庫中取得貼文並將其作為 JSON 傳回。
- src/upload.php: 根據 ID 的存在處理貼文建立和更新。
此解決方案包括設定項目、資料庫配置、HTML 結構、CSS 樣式、使用 AJAX 處理圖像上傳以及使用 PHP PDO 將圖像資料儲存在資料庫中。每行程式碼都附有註解來解釋其目的和功能,使其成為建立具有上傳功能的圖片庫的綜合教學。
連結連結
如果您發現本系列有幫助,請考慮在 GitHub 上給 存儲庫 一個星號或在您最喜歡的社交網絡上分享該帖子? 。您的支持對我來說意義重大!
如果您想要更多類似的有用內容,請隨時關注我:
- 領英
- GitHub
原始碼
以上是PHP 速成課程:簡單圖片庫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

長URL(通常用關鍵字和跟踪參數都混亂)可以阻止訪問者。 URL縮短腳本提供了解決方案,創建了簡潔的鏈接,非常適合社交媒體和其他平台。 這些腳本對於單個網站很有價值

Laravel使用其直觀的閃存方法簡化了處理臨時會話數據。這非常適合在您的應用程序中顯示簡短的消息,警報或通知。 默認情況下,數據僅針對後續請求: $請求 -

這是有關用Laravel後端構建React應用程序的系列的第二個也是最後一部分。在該系列的第一部分中,我們使用Laravel為基本的產品上市應用程序創建了一個RESTFUL API。在本教程中,我們將成為開發人員

Laravel 提供简洁的 HTTP 响应模拟语法,简化了 HTTP 交互测试。这种方法显著减少了代码冗余,同时使您的测试模拟更直观。 基本实现提供了多种响应类型快捷方式: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

PHP客戶端URL(curl)擴展是開發人員的強大工具,可以與遠程服務器和REST API無縫交互。通過利用Libcurl(備受尊敬的多協議文件傳輸庫),PHP curl促進了有效的執行

您是否想為客戶最緊迫的問題提供實時的即時解決方案? 實時聊天使您可以與客戶進行實時對話,並立即解決他們的問題。它允許您為您的自定義提供更快的服務

2025年的PHP景觀調查調查了當前的PHP發展趨勢。 它探討了框架用法,部署方法和挑戰,旨在為開發人員和企業提供見解。 該調查預計現代PHP Versio的增長

在本文中,我們將在Laravel Web框架中探索通知系統。 Laravel中的通知系統使您可以通過不同渠道向用戶發送通知。今天,我們將討論您如何發送通知OV


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)