Hướng dẫn multiple image upload with view edit and delete in php - tải lên nhiều hình ảnh với chế độ xem chỉnh sửa và xóa trong php

Tải lên nhiều hình ảnh cùng một lúc giúp giảm thời gian tải lên một số lượng lớn hình ảnh lên máy chủ. Nó cũng cung cấp một cách thân thiện với người dùng để tải lên nhiều hình ảnh lên máy chủ cùng một lúc thay vì từng người một. Nhiều chức năng tải lên hình ảnh rất hữu ích cho phần Quản lý bộ sưu tập động trên ứng dụng web. Nó cũng rất hữu ích cho phần quản lý sản phẩm, nơi nhiều hình ảnh cần được tải lên cho mỗi sản phẩm. at once helps to reduce the time taking for uploading a large number of images to the server. It also provides a user-friendly way to upload multiple images to the server at once instead of one-by-one. Multiple image upload functionality is very useful for the dynamic gallery management section on the web application. It is also very useful for product management section where multiple images need to be uploaded for each product.

Nhiều hình ảnh có thể được tải lên trên một lần nhấp bằng PHP. Không chỉ các hình ảnh mà bạn còn có thể tải dữ liệu với hình ảnh lên máy chủ bằng PHP và MySQL. Trong hướng dẫn này, chúng tôi sẽ chỉ cho bạn cách tải lên nhiều hình ảnh và quản lý dữ liệu (xem, chỉnh sửa và xóa) với PHP và MySQL.upload multiple images and manage (view, edit, and delete) data with PHP and MySQL.

Trong tập lệnh ví dụ, chúng tôi sẽ triển khai một hệ thống quản lý bộ sưu tập với nhiều hình ảnh bằng PHP và MySQL.

  • Lấy thông tin thư viện từ cơ sở dữ liệu và liệt kê trên trang web.
  • Tải lên nhiều hình ảnh lên máy chủ và thêm dữ liệu biểu mẫu vào cơ sở dữ liệu.
  • Xem bộ sưu tập với nhiều hình ảnh.
  • Chỉnh sửa và cập nhật nhiều hình ảnh.
  • Xóa thư viện và nhiều hình ảnh.

Trước khi bắt đầu, hãy xem cấu trúc tệp của tập lệnh quản lý tải lên nhiều hình ảnh.

multiple_image_upload_crud/
├── index.php
├── view.php
├── addEdit.php
├── postAction.php
├── DB.class.php
├── uploads/
│   └── images/
├── js/
│   └── jquery.min.js
├── bootstrap/
│   └── bootstrap.min.css
├── css/
│   └── style.css
└── images/

Tạo bảng cơ sở dữ liệu

Để lưu trữ thông tin về bộ sưu tập và hình ảnh, hai bảng cần được tạo trong cơ sở dữ liệu.

1. SQL sau đây tạo bảng

CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
1 với một số trường cơ bản trong cơ sở dữ liệu MySQL. The following SQL creates a
CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
1 table with some basic fields in the MySQL database.

CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

2. SQL sau đây tạo bảng

CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
2 với trường Định danh thư viện mẹ (Gallery_id) trong cơ sở dữ liệu MySQL. The following SQL creates a
CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
2 table with parent gallery identifier field (gallery_id) in the MySQL database.

CREATE TABLE `gallery_images` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `gallery_id` int(11) NOT NULL,
 `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `uploaded_on` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Lớp cơ sở dữ liệu (db.class.php)

Lớp DB xử lý tất cả các hoạt động liên quan đến cơ sở dữ liệu (kết nối, chèn, cập nhật và xóa). Chỉ định máy chủ cơ sở dữ liệu (

CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
3), tên người dùng (
CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
4), mật khẩu (
CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
5) và tên (
CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
6) theo thông tin xác thực cơ sở dữ liệu MySQL của bạn.

  • __construct () - Kết nối với cơ sở dữ liệu với tiện ích mở rộng PHP và MySQLI. – Connect to the database with PHP and MySQLi Extension.
  • getrows () -
    • Lấy bộ sưu tập với hình ảnh từ cơ sở dữ liệu dựa trên các điều kiện được chỉ định.
    • Nếu một hàng được yêu cầu, dữ liệu bộ sưu tập với tất cả các hình ảnh tương ứng sẽ được trả về. Mặt khác, chỉ có một hình ảnh được trả về với dữ liệu bộ sưu tập.
  • getImgrow () - tìm nạp dữ liệu hình ảnh từ cơ sở dữ liệu dựa trên ID được chỉ định. – Fetch the image data from the database based on the specified ID.
  • Chèn () - Chèn dữ liệu thư viện vào cơ sở dữ liệu. – Insert gallery data into the database.
  • InsertImage () - Chèn hình ảnh thư viện trong cơ sở dữ liệu. – Insert gallery images in the database.
  • Cập nhật () - Cập nhật dữ liệu thư viện vào cơ sở dữ liệu. – Update gallery data into the database.
  • Xóa () - Xóa dữ liệu thư viện khỏi cơ sở dữ liệu. – Delete gallery data from the database.
  • DeleteImage () - Xóa hình ảnh của bộ sưu tập cụ thể khỏi cơ sở dữ liệu. – Delete image of the specific gallery from the database.
/* 
 * DB Class
 * This class is used for database related (connect, insert, update, and delete) operations
 * @author    CodexWorld.com
 * @url        http://www.codexworld.com
 * @license    http://www.codexworld.com/license
 */
class DB{
    private 
$dbHost     "localhost";
    private 
$dbUsername "root";
    private 
$dbPassword "root";
    private 
$dbName     "codexworld";
    private 
$galleryTbl "gallery";
    private 
$imgTbl     "gallery_images";

         public function

__construct(){
        if(!isset(
$this->db)){
            
// Connect to the database
            
$conn = new mysqli($this->dbHost$this->dbUsername$this->dbPassword$this->dbName);
            if(
$conn->connect_error){
                die(
"Failed to connect with MySQL: " $conn->connect_error);
            }else{
                
$this->db $conn;
            }
        }
    }
/*
     * Returns rows from the database based on the conditions
     * @param string name of the table
     * @param array select, where, order_by, limit and return_type conditions
     */
    
public function getRows($conditions = array()){
        
$sql 'SELECT ';
        
$sql .= '*, (SELECT file_name FROM '.$this->imgTbl.' WHERE gallery_id = '.$this->galleryTbl.'.id ORDER BY id DESC LIMIT 1) as default_image';
        
$sql .= ' FROM '.$this->galleryTbl;
        if(
array_key_exists("where",$conditions)){
            
$sql .= ' WHERE ';
            
$i 0;
            foreach(
$conditions['where'] as $key => $value){
                
$pre = ($i 0)?' AND ':'';
                
$sql .= $pre.$key." = '".$value."'";
                
$i++;
            }
        }

                 if(

array_key_exists("order_by",$conditions)){
            
$sql .= ' ORDER BY '.$conditions['order_by']; 
        }else{
            
$sql .= ' ORDER BY id DESC '
        }

                 if(

array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
            
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit']; 
        }elseif(!
array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
            
$sql .= ' LIMIT '.$conditions['limit']; 
        }
$result $this->db->query($sql);

                 if(

array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
            switch(
$conditions['return_type']){
                case 
'count':
                    
$data $result->num_rows;
                    break;
                case 
'single':
                    
$data $result->fetch_assoc();

                                         if(!empty(

$data)){
                        
$sql 'SELECT * FROM '.$this->imgTbl.' WHERE gallery_id = '.$data['id'];
                        
$result $this->db->query($sql);
                        
$imgData = array();
                        if(
$result->num_rows 0){
                            while(
$row $result->fetch_assoc()){
                                
$imgData[] = $row;
                            }
                        }
                        
$data['images'] = $imgData;
                    }
                    break;
                default:
                    
$data '';
            }
        }else{
            if(
$result->num_rows 0){
                while(
$row $result->fetch_assoc()){
                    
$data[] = $row;
                }
            }
        }
        return !empty(
$data)?$data:false;
    }

         public function

getImgRow($id){
        
$sql 'SELECT * FROM '.$this->imgTbl.' WHERE id = '.$id;
        
$result $this->db->query($sql);
        return (
$result->num_rows 0)?$result->fetch_assoc():false;
    }
/*
     * Insert data into the database
     * @param string name of the table
     * @param array the data for inserting into the table
     */
    
public function insert($data){
        if(!empty(
$data) && is_array($data)){
            
$columns '';
            
$values  '';
            
$i 0;
            if(!
array_key_exists('created',$data)){
                
$data['created'] = date("Y-m-d H:i:s");
            }
            if(!
array_key_exists('modified',$data)){
                
$data['modified'] = date("Y-m-d H:i:s");
            }
            foreach(
$data as $key=>$val){
                
$pre = ($i 0)?', ':'';
                
$columns .= $pre.$key;
                
$values  .= $pre."'".$this->db->real_escape_string($val)."'";
                
$i++;
            }
            
$query "INSERT INTO ".$this->galleryTbl." (".$columns.") VALUES (".$values.")";
            
$insert $this->db->query($query);
            return 
$insert?$this->db->insert_id:false;
        }else{
            return 
false;
        }
    }

         public function

insertImage($data){
        if(!empty(
$data) && is_array($data)){
            
$columns '';
            
$values  '';
            
$i 0;
            if(!
array_key_exists('uploaded_on',$data)){
                
$data['uploaded_on'] = date("Y-m-d H:i:s");
            }
            foreach(
$data as $key=>$val){
                
$pre = ($i 0)?', ':'';
                
$columns .= $pre.$key;
                
$values  .= $pre."'".$this->db->real_escape_string($val)."'";
                
$i++;
            }
            
$query "INSERT INTO ".$this->imgTbl." (".$columns.") VALUES (".$values.")";
            
$insert $this->db->query($query);
            return 
$insert?$this->db->insert_id:false;
        }else{
            return 
false;
        }
    }
/*
     * Update data into the database
     * @param string name of the table
     * @param array the data for updating into the table
     * @param array where condition on updating data
     */
    
public function update($data$conditions){
        if(!empty(
$data) && is_array($data)){
            
$colvalSet '';
            
$whereSql '';
            
$i 0;
            if(!
array_key_exists('modified',$data)){
                
$data['modified'] = date("Y-m-d H:i:s");
            }
            foreach(
$data as $key=>$val){
                
$pre = ($i 0)?', ':'';
                
$colvalSet .= $pre.$key."='".$this->db->real_escape_string($val)."'";
                
$i++;
            }
            if(!empty(
$conditions)&& is_array($conditions)){
                
$whereSql .= ' WHERE ';
                
$i 0;
                foreach(
$conditions as $key => $value){
                    
$pre = ($i 0)?' AND ':'';
                    
$whereSql .= $pre.$key." = '".$value."'";
                    
$i++;
                }
            }
            
$query "UPDATE ".$this->galleryTbl." SET ".$colvalSet.$whereSql;
            
$update $this->db->query($query);
            return 
$update?$this->db->affected_rows:false;
        }else{
            return 
false;
        }
    }
/*
     * Delete data from the database
     * @param string name of the table
     * @param array where condition on deleting data
     */
    
public function delete($conditions){
        
$whereSql '';
        if(!empty(
$conditions)&& is_array($conditions)){
            
$whereSql .= ' WHERE ';
            
$i 0;
            foreach(
$conditions as $key => $value){
                
$pre = ($i 0)?' AND ':'';
                
$whereSql .= $pre.$key." = '".$value."'";
                
$i++;
            }
        }
        
$query "DELETE FROM ".$this->galleryTbl.$whereSql;
        
$delete $this->db->query($query);
        return 
$delete?true:false;
    }

         public function

deleteImage($conditions){
        
$whereSql '';
        if(!empty(
$conditions)&& is_array($conditions)){
            
$whereSql .= ' WHERE ';
            
$i 0;
            foreach(
$conditions as $key => $value){
                
$pre = ($i 0)?' AND ':'';
                
$whereSql .= $pre.$key." = '".$value."'";
                
$i++;
            }
        }
        
$query "DELETE FROM ".$this->imgTbl.$whereSql;
        
$delete $this->db->query($query);
        return 
$delete?true:false;
    }
}

Thư viện bootstrap

Thư viện Bootstrap 4 được sử dụng để thiết kế bảng, danh sách, trường biểu mẫu và liên kết. Vì vậy, bao gồm tệp CSS của thư viện Bootstrap. Nếu bạn không muốn sử dụng bootstrap, hãy bỏ qua nó bao gồm.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

Danh sách thư viện (index.php)

Ban đầu, tất cả các dữ liệu bộ sưu tập được lấy từ cơ sở dữ liệu và được liệt kê trong chế độ xem bảng với chế độ xem, thêm, chỉnh sửa và xóa các nút.

  • Liên kết xem cho phép xem hình ảnh của bộ sưu tập.View link allows viewing the images of the gallery.
  • Liên kết Thêm cho phép tải lên thông tin thư viện với nhiều hình ảnh.Add link allows uploading gallery information with multiple images.
  • Liên kết Chỉnh sửa cho phép chỉnh sửa thông tin thư viện và tải lên/xóa hình ảnh khỏi bộ sưu tập.Edit link allows to edit gallery info and upload/delete images from the gallery.
  • Liên kết xóa cho phép xóa thư viện và hình ảnh khỏi cơ sở dữ liệu.Delete link allows deleting gallery and images from the database.
  • Huy hiệu trạng thái (hoạt động/không hoạt động) cho phép kiểm soát khả năng hiển thị của bộ sưu tập.Status badge (Active/Inactive) allows controlling the visibility of the gallery.
// Start session 
session_start(); // Include and initialize DB class
require_once 'DB.class.php';
$db = new DB(); // Fetch the gallery data
$images $db->getRows(); // Get session data
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:''; // Get status message from session
if(!empty($sessData['status']['msg'])){
    
$statusMsg $sessData['status']['msg'];
    
$statusMsgType $sessData['status']['type'];
    unset(
$_SESSION['sessData']['status']);
}
?> if(!empty($statusMsg)){ ?> <div class="col-xs-12"> <div class="alert alert-echo $statusMsgType?>">echo $statusMsg?>div> div> ?> <div class="row"> <div class="col-md-12 head"> <h5>Imagesh5> <div class="float-right"> <a href="addEdit.php" class="btn btn-success"><i class="plus">i> New Gallerya> div> div> <table class="table table-striped table-bordered"> <thead class="thead-dark"> <tr> <th width="5%">#th> <th width="10%">th> <th width="40%">Titleth> <th width="19%">Createdth> <th width="8%">Statusth> <th width="18%">Actionth> tr> thead> <tbody>                         if(!empty($images)){ $i=0;
                foreach(
$images as $row){ $i++;
                    
$defaultImage = !empty($row['default_image'])?'':'';
                    
$statusLink = ($row['status'] == 1)?'postAction.php?action_type=block&id='.$row['id']:'postAction.php?action_type=unblock&id='.$row['id'];
                    
$statusTooltip = ($row['status'] == 1)?'Click to Inactive':'Click to Active';
            
?> <tr> <td>echo $i?>td> <td>echo $defaultImage?>td> <td>echo $row['title']; ?>td> <td>echo $row['created']; ?>td> <td><a href="echo $statusLink?>" title="echo $statusTooltip?>"><span class="badge echo ($row['status'] == 1)?'badge-success':'badge-danger'?>">echo ($row['status'] == 1)?'Active':'Inactive'?>span>a>td> <td> <a href="view.php?id=echo $row['id']; ?>" class="btn btn-primary">viewa> <a href="addEdit.php?id=echo $row['id']; ?>" class="btn btn-warning">edita> <a href="postAction.php?action_type=delete&id=echo $row['id']; ?>" class="btn btn-danger" onclick="return confirm('Are you sure to delete data?')?true:false;">deletea> td> tr> } }else{ ?> <tr><td colspan="6">No gallery found...td>tr> ?> tbody> table> div>

Xóa hình ảnh thư viện thông qua Ajax

Trong các tệp

CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
7 và
CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
8, hình ảnh xóa chức năng được tích hợp. JQuery được sử dụng để xóa hình ảnh từ bộ sưu tập thông qua Ajax.

Bao gồm thư viện jQuery nơi sử dụng chức năng xóa hình ảnh của bộ sưu tập.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">script>

Hàm Xóa () Bắt đầu yêu cầu AJAX để xóa hình ảnh khỏi thư viện.deleteImage() function initiate AJAX request to delete image from gallery.

  • Đăng ID tệp lên tệp
    CREATE TABLE `gallery` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
     `created` datetime NOT NULL,
     `modified` datetime NOT NULL,
     `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    9.
  • Hình ảnh được chỉ định bị xóa khỏi cơ sở dữ liệu và phần tử được xóa khỏi trang web.
<script>
function deleteImage(id){
    var result = confirm("Are you sure to delete?");
    if(result){
        $.post( "postAction.php", {action_type:"img_delete",id:id}, function(resp) {
            if(resp == 'ok'){
                $('#imgb_'+id).remove();
                alert('The image has been removed from the gallery');
            }else{
                alert('Some problem occurred, please try again.');
            }
        });
    }
}
script>

Hiển thị nhiều hình ảnh với thông tin thư viện (View.php)

Trong tệp

CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
7, thông tin thư viện được hiển thị.

  • Tất cả các hình ảnh từ bộ sưu tập được liệt kê với liên kết xóa.
  • Sau khi nhấp vào nút Xóa, hàm
    CREATE TABLE `gallery_images` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `gallery_id` int(11) NOT NULL,
     `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
     `uploaded_on` datetime NOT NULL,
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    1 được kích hoạt và hình ảnh tương ứng được xóa khỏi bộ sưu tập thông qua JQuery AJAX bằng PHP.
if(empty($_GET['id'])){ 
    
header("Location: manage.php");
}
// Include and initialize DB class
require_once 'DB.class.php';
$db = new DB(); $conditions['where'] = array(
    
'id' => $_GET['id'],
);
$conditions['return_type'] = 'single';
$galData $db->getRows($conditions);
?> <div class="row"> <div class="col-md-12"> <h5>echo !empty($galData['title'])?$galData['title']:''?>h5> if(!empty($galData['images'])){ ?> <div class="gallery-img"> foreach($galData['images'] as $imgRow){ ?> <div class="img-box" id="imgb_echo $imgRow['id']; ?>"> <img src="uploads/images/echo $imgRow['file_name']; ?>"> <a href="javascript:void(0);" class="badge badge-danger" onclick="deleteImage('echo $imgRow['id']; ?>')">deletea> div> ?> div> ?> div> <a href="index.php" class="btn btn-primary">Back to Lista> div>

Nhiều hình ảnh tải lên và biểu mẫu thêm/chỉnh sửa dữ liệu (bổ sung.php)

Tệp

CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
8 giữ biểu mẫu HTML cho phép người dùng chọn nhiều tệp hình ảnh và cung cấp tên thư viện.

  • Ban đầu, dữ liệu biểu mẫu được gửi tới tập lệnh PHP (
    CREATE TABLE `gallery` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
     `created` datetime NOT NULL,
     `modified` datetime NOT NULL,
     `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    9) để tải lên nhiều hình ảnh và chèn dữ liệu biểu mẫu vào cơ sở dữ liệu.
  • Nếu tham số ID tồn tại trên URL,
    • Dữ liệu bộ sưu tập hiện tại sẽ được lấy từ cơ sở dữ liệu.
    • Dữ liệu được điền sẵn trong các trường đầu vào và hình ảnh được liệt kê trong trường Tải lên tệp.
    • Dữ liệu được gửi tới tập lệnh PHP (
      CREATE TABLE `gallery` (
       `id` int(11) NOT NULL AUTO_INCREMENT,
       `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
       `created` datetime NOT NULL,
       `modified` datetime NOT NULL,
       `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
       PRIMARY KEY (`id`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
      9) để cập nhật bản ghi hiện có trong cơ sở dữ liệu và tải hình ảnh mới lên máy chủ.
// Start session 
session_start(); $postData $galData = array(); // Get session data
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:''; // Get status message from session
if(!empty($sessData['status']['msg'])){
    
$statusMsg $sessData['status']['msg'];
    
$statusMsgType $sessData['status']['type'];
    unset(
$_SESSION['sessData']['status']);
}
// Get posted data from session
if(!empty($sessData['postData'])){
    
$postData $sessData['postData'];
    unset(
$_SESSION['sessData']['postData']);
}
// Get gallery data
if(!empty($_GET['id'])){
    
// Include and initialize DB class
    
require_once 'DB.class.php';
    
$db = new DB(); $conditions['where'] = array(
        
'id' => $_GET['id'],
    );
    
$conditions['return_type'] = 'single';
    
$galData $db->getRows($conditions);
}
// Pre-filled data
$galData = !empty($postData)?$postData:$galData; // Define action
$actionLabel = !empty($_GET['id'])?'Edit':'Add';
?> <div class="container"> <h2>echo $actionLabel?> Galleryh2> <hr> if(!empty($statusMsg)){ ?> <div class="col-xs-12"> <div class="alert alert-echo $statusMsgType?>">echo $statusMsg?>div> div> ?> <div class="row"> <div class="col-md-6"> <form method="post" action="postAction.php" enctype="multipart/form-data"> <div class="form-group"> <label>Images:label> <input type="file" name="images[]" class="form-control" multiple> if(!empty($galData['images'])){ ?> <div class="gallery-img"> foreach($galData['images'] as $imgRow){ ?> <div class="img-box" id="imgb_echo $imgRow['id']; ?>"> <img src="uploads/images/echo $imgRow['file_name']; ?>"> <a href="javascript:void(0);" class="badge badge-danger" onclick="deleteImage('echo $imgRow['id']; ?>')">deletea> div> ?> div> ?> div> <div class="form-group"> <label>Title:label> <input type="text" name="title" class="form-control" placeholder="Enter title" value="echo !empty($galData['title'])?$galData['title']:''?>" > div> <a href="index.php" class="btn btn-secondary">Backa> <input type="hidden" name="id" value="echo !empty($galData['id'])?$galData['id']:''?>"> <input type="submit" name="imgSubmit" class="btn btn-success" value="SUBMIT"> form> div> div> div>

Tải lên nhiều hình ảnh, thêm, chỉnh sửa và xóa bản ghi (postaction.php)

Tệp này xử lý nhiều tệp tải lên và thêm, chỉnh sửa và xóa các hoạt động bằng PHP và MySQL.

1. Thêm / chỉnh sửa biểu mẫu Gửi:

  • Dữ liệu biểu mẫu được gửi được xác thực để kiểm tra giá trị trường trống.
  • Các phương thức
    CREATE TABLE `gallery_images` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `gallery_id` int(11) NOT NULL,
     `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
     `uploaded_on` datetime NOT NULL,
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    5 và
    CREATE TABLE `gallery_images` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `gallery_id` int(11) NOT NULL,
     `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
     `uploaded_on` datetime NOT NULL,
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    6 của lớp DB được sử dụng để thêm/cập nhật dữ liệu bộ sưu tập vào cơ sở dữ liệu.
  • Kiểm tra và xác thực tiện ích mở rộng tệp bằng hàm pathinfo () trong PHP.pathinfo() function in PHP.
  • Tải lên nhiều hình ảnh lên máy chủ bằng cách sử dụng hàm move_uploaded_file () trong PHP.move_uploaded_file() function in PHP.
  • Chèn tên tệp và ID bộ sưu tập được tải lên trong cơ sở dữ liệu bằng phương thức
    CREATE TABLE `gallery_images` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `gallery_id` int(11) NOT NULL,
     `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
     `uploaded_on` datetime NOT NULL,
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    7 của lớp DB.

2. Bộ sưu tập không hoạt động (action_type => block):

  • Cập nhật và đặt trạng thái thư viện thành 0 trong cơ sở dữ liệu.
  • Phương thức
    CREATE TABLE `gallery_images` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `gallery_id` int(11) NOT NULL,
     `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
     `uploaded_on` datetime NOT NULL,
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    6 của lớp DB được sử dụng để cập nhật giá trị trường trạng thái trong cơ sở dữ liệu.

3. Kích hoạt bộ sưu tập (Action_Type => bỏ chặn):

  • Cập nhật và đặt trạng thái bộ sưu tập thành 1 trong cơ sở dữ liệu.
  • Phương thức
    CREATE TABLE `gallery_images` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `gallery_id` int(11) NOT NULL,
     `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
     `uploaded_on` datetime NOT NULL,
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    6 của lớp DB được sử dụng để cập nhật giá trị trường trạng thái trong cơ sở dữ liệu.

3. Kích hoạt bộ sưu tập (Action_Type => bỏ chặn):

  • Cập nhật và đặt trạng thái bộ sưu tập thành 1 trong cơ sở dữ liệu.
  • 4. Xóa thư viện (action_type => xóa):
  • Xóa thư viện và dữ liệu hình ảnh khỏi cơ sở dữ liệu.

Xóa hình ảnh khỏi thư mục của máy chủ.

  • Các phương thức
    /* 
     * DB Class
     * This class is used for database related (connect, insert, update, and delete) operations
     * @author    CodexWorld.com
     * @url        http://www.codexworld.com
     * @license    http://www.codexworld.com/license
     */
    class DB{
        private 
    $dbHost     "localhost";
        private 
    $dbUsername "root";
        private 
    $dbPassword "root";
        private 
    $dbName     "codexworld";
        private 
    $galleryTbl "gallery";
        private 
    $imgTbl     "gallery_images";

             public function

    __construct(){
            if(!isset(
    $this->db)){
                
    // Connect to the database
                
    $conn = new mysqli($this->dbHost$this->dbUsername$this->dbPassword$this->dbName);
                if(
    $conn->connect_error){
                    die(
    "Failed to connect with MySQL: " $conn->connect_error);
                }else{
                    
    $this->db $conn;
                }
            }
        }
    /*
         * Returns rows from the database based on the conditions
         * @param string name of the table
         * @param array select, where, order_by, limit and return_type conditions
         */
        
    public function getRows($conditions = array()){
            
    $sql 'SELECT ';
            
    $sql .= '*, (SELECT file_name FROM '.$this->imgTbl.' WHERE gallery_id = '.$this->galleryTbl.'.id ORDER BY id DESC LIMIT 1) as default_image';
            
    $sql .= ' FROM '.$this->galleryTbl;
            if(
    array_key_exists("where",$conditions)){
                
    $sql .= ' WHERE ';
                
    $i 0;
                foreach(
    $conditions['where'] as $key => $value){
                    
    $pre = ($i 0)?' AND ':'';
                    
    $sql .= $pre.$key." = '".$value."'";
                    
    $i++;
                }
            }

                     if(

    array_key_exists("order_by",$conditions)){
                
    $sql .= ' ORDER BY '.$conditions['order_by']; 
            }else{
                
    $sql .= ' ORDER BY id DESC '
            }

                     if(

    array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
                
    $sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit']; 
            }elseif(!
    array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
                
    $sql .= ' LIMIT '.$conditions['limit']; 
            }
    $result $this->db->query($sql);

                     if(

    array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
                switch(
    $conditions['return_type']){
                    case 
    'count':
                        
    $data $result->num_rows;
                        break;
                    case 
    'single':
                        
    $data $result->fetch_assoc();

                                             if(!empty(

    $data)){
                            
    $sql 'SELECT * FROM '.$this->imgTbl.' WHERE gallery_id = '.$data['id'];
                            
    $result $this->db->query($sql);
                            
    $imgData = array();
                            if(
    $result->num_rows 0){
                                while(
    $row $result->fetch_assoc()){
                                    
    $imgData[] = $row;
                                }
                            }
                            
    $data['images'] = $imgData;
                        }
                        break;
                    default:
                        
    $data '';
                }
            }else{
                if(
    $result->num_rows 0){
                    while(
    $row $result->fetch_assoc()){
                        
    $data[] = $row;
                    }
                }
            }
            return !empty(
    $data)?$data:false;
        }

             public function

    getImgRow($id){
            
    $sql 'SELECT * FROM '.$this->imgTbl.' WHERE id = '.$id;
            
    $result $this->db->query($sql);
            return (
    $result->num_rows 0)?$result->fetch_assoc():false;
        }
    /*
         * Insert data into the database
         * @param string name of the table
         * @param array the data for inserting into the table
         */
        
    public function insert($data){
            if(!empty(
    $data) && is_array($data)){
                
    $columns '';
                
    $values  '';
                
    $i 0;
                if(!
    array_key_exists('created',$data)){
                    
    $data['created'] = date("Y-m-d H:i:s");
                }
                if(!
    array_key_exists('modified',$data)){
                    
    $data['modified'] = date("Y-m-d H:i:s");
                }
                foreach(
    $data as $key=>$val){
                    
    $pre = ($i 0)?', ':'';
                    
    $columns .= $pre.$key;
                    
    $values  .= $pre."'".$this->db->real_escape_string($val)."'";
                    
    $i++;
                }
                
    $query "INSERT INTO ".$this->galleryTbl." (".$columns.") VALUES (".$values.")";
                
    $insert $this->db->query($query);
                return 
    $insert?$this->db->insert_id:false;
            }else{
                return 
    false;
            }
        }

             public function

    insertImage($data){
            if(!empty(
    $data) && is_array($data)){
                
    $columns '';
                
    $values  '';
                
    $i 0;
                if(!
    array_key_exists('uploaded_on',$data)){
                    
    $data['uploaded_on'] = date("Y-m-d H:i:s");
                }
                foreach(
    $data as $key=>$val){
                    
    $pre = ($i 0)?', ':'';
                    
    $columns .= $pre.$key;
                    
    $values  .= $pre."'".$this->db->real_escape_string($val)."'";
                    
    $i++;
                }
                
    $query "INSERT INTO ".$this->imgTbl." (".$columns.") VALUES (".$values.")";
                
    $insert $this->db->query($query);
                return 
    $insert?$this->db->insert_id:false;
            }else{
                return 
    false;
            }
        }
    /*
         * Update data into the database
         * @param string name of the table
         * @param array the data for updating into the table
         * @param array where condition on updating data
         */
        
    public function update($data$conditions){
            if(!empty(
    $data) && is_array($data)){
                
    $colvalSet '';
                
    $whereSql '';
                
    $i 0;
                if(!
    array_key_exists('modified',$data)){
                    
    $data['modified'] = date("Y-m-d H:i:s");
                }
                foreach(
    $data as $key=>$val){
                    
    $pre = ($i 0)?', ':'';
                    
    $colvalSet .= $pre.$key."='".$this->db->real_escape_string($val)."'";
                    
    $i++;
                }
                if(!empty(
    $conditions)&& is_array($conditions)){
                    
    $whereSql .= ' WHERE ';
                    
    $i 0;
                    foreach(
    $conditions as $key => $value){
                        
    $pre = ($i 0)?' AND ':'';
                        
    $whereSql .= $pre.$key." = '".$value."'";
                        
    $i++;
                    }
                }
                
    $query "UPDATE ".$this->galleryTbl." SET ".$colvalSet.$whereSql;
                
    $update $this->db->query($query);
                return 
    $update?$this->db->affected_rows:false;
            }else{
                return 
    false;
            }
        }
    /*
         * Delete data from the database
         * @param string name of the table
         * @param array where condition on deleting data
         */
        
    public function delete($conditions){
            
    $whereSql '';
            if(!empty(
    $conditions)&& is_array($conditions)){
                
    $whereSql .= ' WHERE ';
                
    $i 0;
                foreach(
    $conditions as $key => $value){
                    
    $pre = ($i 0)?' AND ':'';
                    
    $whereSql .= $pre.$key." = '".$value."'";
                    
    $i++;
                }
            }
            
    $query "DELETE FROM ".$this->galleryTbl.$whereSql;
            
    $delete $this->db->query($query);
            return 
    $delete?true:false;
        }

             public function

    deleteImage($conditions){
            
    $whereSql '';
            if(!empty(
    $conditions)&& is_array($conditions)){
                
    $whereSql .= ' WHERE ';
                
    $i 0;
                foreach(
    $conditions as $key => $value){
                    
    $pre = ($i 0)?' AND ':'';
                    
    $whereSql .= $pre.$key." = '".$value."'";
                    
    $i++;
                }
            }
            
    $query "DELETE FROM ".$this->imgTbl.$whereSql;
            
    $delete $this->db->query($query);
            return 
    $delete?true:false;
        }
    }
    0 và
    CREATE TABLE `gallery_images` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `gallery_id` int(11) NOT NULL,
     `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
     `uploaded_on` datetime NOT NULL,
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    1 của lớp DB được sử dụng để xóa dữ liệu bộ sưu tập và hình ảnh khỏi cơ sở dữ liệu.
  • 5. Xóa hình ảnh (action_type => img_delete):
  • Xóa dữ liệu hình ảnh khỏi cơ sở dữ liệu.

Xóa tệp hình ảnh khỏi thư mục của máy chủ.

CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
0

Phương pháp

CREATE TABLE `gallery_images` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `gallery_id` int(11) NOT NULL,
 `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `uploaded_on` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
1 của lớp DB được sử dụng để xóa dữ liệu hình ảnh khỏi cơ sở dữ liệu.

Sau khi thao tác dữ liệu, trạng thái được lưu trữ trong phiên PHP và chuyển hướng đến trang tương ứng.

Php crud hoạt động với tìm kiếm và phân trangmultiple images upload management script is very useful for dynamic data management section in the web application. This script can be used for many purposes, like products management with multiple images using PHP and MySQL. You can easily enhance the functionality of this script and use in any data management section where multiple image upload functionality is needed.

Sự kết luận

Tập lệnh quản lý tải lên nhiều hình ảnh này rất hữu ích cho phần quản lý dữ liệu động trong ứng dụng web. Kịch bản này có thể được sử dụng cho nhiều mục đích, như quản lý sản phẩm với nhiều hình ảnh sử dụng PHP và MySQL. Bạn có thể dễ dàng tăng cường chức năng của tập lệnh này và sử dụng trong bất kỳ phần quản lý dữ liệu nào trong đó cần nhiều chức năng tải lên hình ảnh.

Ví dụ về việc tải lên nhiều tệp và hình ảnh trong Codeigniter.

Ví dụ về việc tải lên nhiều tệp và hình ảnh trong Codeigniter..
Làm thế nào tôi có thể tải lên hình ảnh trong PHP?
Tạo biểu mẫu HTML.
Chọn hình ảnh để tải lên:.

Tải lên nhiều tệp trong PHP (Tải lên ..

Bao gồm tệp cấu hình cơ sở dữ liệu để kết nối và chọn cơ sở dữ liệu MySQL ..Create an HTML form to select multiple images and files. Display multiple images preview before sending to server. Implement necessary validation before uploading. Save files in the local directory and store the uploaded file path in the database.

Làm thế nào có thể tải lên nhiều hình ảnh trong Codeigniter?

Để tải lên nhiều tệp, chúng tôi sẽ sử dụng thư viện tải lên trong Codeigniter.Thư viện này sử dụng thư mục tải lên để lưu tất cả các tệp và hình ảnh ...
Làm thế nào có thể tải lên nhiều hình ảnh trong Codeigniter?
.
.
Ví dụ về việc tải lên nhiều tệp và hình ảnh trong Codeigniter.
.
.

Làm thế nào tôi có thể tải lên hình ảnh trong PHP?

Tạo biểu mẫu HTML..
.
.
.
Chọn hình ảnh để tải lên:.
.
.
.
.