Multiple Image Upload With View, Edit And Delete In PHP Example
Teams applying “Multiple Image Upload With View, Edit And Delete In PHP Example” in a production project can use learn more here to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.
Before copying the example into a live application, confirm version-specific behaviour with the PHP project and test it against the project’s actual database and runtime.
Hi guys,
Today i will explained how to Upload Multiple Images With View, Edit And Delete In PHP. This example is so easy to use in php. THis example to I am upload to the multiple images and add,delete,show ,and edit in image gallery in php.
This exampel To i am create a uploads/images folder and five files to addEdit.php,Db.class.php,index.php,postAction.php and view.php File create.
So let's start to the example.
Index.php
<?php
session_start();
require_once 'DB.class.php';
$db = new DB();
$images = $db->getRows();
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
if(!empty($sessData['status']['msg'])){
$statusMsg = $sessData['status']['msg'];
$statusMsgType = $sessData['status']['type'];
unset($_SESSION['sessData']['status']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<?php if(!empty($statusMsg)){ ?>
<div class="col-xs-12">
<div class="alert alert-<?php echo $statusMsgType; ?>"><?php echo $statusMsg; ?></div>
</div>
<?php } ?>
<div class="row">
<div class="col-md-12">
<!-- Add link -->
<div class="float-right p-2">
<a href="addEdit.php" class="btn btn-success"><i class="plus"></i> New Gallery</a>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-12">
<table class="table table-striped table-bordered">
<thead class="thead-dark">
<tr>
<th width="5%">#</th>
<th width="10%"></th>
<th width="40%">Title</th>
<th width="19%">Created</th>
<th width="6%">Status</th>
<th width="20%">Action</th>
</tr>
</thead>
<tbody>
<?php
if(!empty($images)){
$i=0;
foreach($images as $row){
$i++;
$defaultImage = !empty($row['default_image'])?'<img style="width:100px;" src="uploads/images/'.$row['default_image'].'" alt="" />':'';
$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><?php echo $i; ?></td>
<td width="50px;"><?php echo $defaultImage; ?></td>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['created']; ?></td>
<td><a href="<?php echo $statusLink; ?>" title="<?php echo $statusTooltip; ?>"><span class="badge <?php echo ($row['status'] == 1)?'badge-success':'badge-danger'; ?>"><?php echo ($row['status'] == 1)?'Active':'Inactive'; ?></span></a></td>
<td>
<a href="view.php?id=<?php echo $row['id']; ?>" class="btn btn-primary">view</a>
<a href="addEdit.php?id=<?php echo $row['id']; ?>" class="btn btn-warning">edit</a>
<a href="postAction.php?action_type=delete&id=<?php echo $row['id']; ?>" class="btn btn-danger" onclick="return confirm('Are you sure to delete data?')?true:false;">delete</a>
</td>
</tr>
<?php } }else{ ?>
<tr><td colspan="6">No gallery found...</td></tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</body>
</html>
DB.class.php
<?php
class DB{
private $dbHost = "localhost";
private $dbUsername = "root";
private $dbPassword = "root";
private $dbName = "login";
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;
}
}
?>
addEdit.php
<?php
session_start();
$postData = $galData = array();
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
if(!empty($sessData['status']['msg'])){
$statusMsg = $sessData['status']['msg'];
$statusMsgType = $sessData['status']['type'];
unset($_SESSION['sessData']['status']);
}
if(!empty($sessData['postData'])){
$postData = $sessData['postData'];
unset($_SESSION['sessData']['postData']);
}
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);
}
$galData = !empty($postData)?$postData:$galData;
$actionLabel = !empty($_GET['id'])?'Edit':'Add';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="container">
<h1><?php echo $actionLabel; ?> Gallery</h1>
<hr>
<?php if(!empty($statusMsg)){ ?>
<div class="col-xs-12">
<div class="alert alert-<?php echo $statusMsgType; ?>"><?php echo $statusMsg; ?></div>
</div>
<?php } ?>
<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>
<?php if(!empty($galData['images'])){ ?>
<div class="gallery-img">
<?php foreach($galData['images'] as $imgRow){ ?>
<div class="img-box" id="imgb_<?php echo $imgRow['id']; ?>">
<img src="uploads/images/<?php echo $imgRow['file_name']; ?>">
<a href="javascript:void(0);" class="badge badge-danger" onclick="deleteImage('<?php echo $imgRow['id']; ?>')">delete</a>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
<div class="form-group">
<label>Title:</label>
<input type="text" name="title" class="form-control" placeholder="Enter title" value="<?php echo !empty($galData['title'])?$galData['title']:''; ?>" >
</div>
<a href="index.php" class="btn btn-secondary">Back</a>
<input type="hidden" name="id" value="<?php echo !empty($galData['id'])?$galData['id']:''; ?>">
<input type="submit" name="imgSubmit" class="btn btn-success" value="SUBMIT">
</form>
</div>
</div>
</div>
</body>
</html>
postAction.php
<?php
session_start();
require_once 'DB.class.php';
$db = new DB();
$uploadDir = "uploads/images/";
$allowTypes = array('jpg','png','jpeg','gif');
$redirectURL = 'index.php';
$statusMsg = $errorMsg = '';
$sessData = array();
$statusType = 'danger';
if(isset($_POST['imgSubmit'])){
$redirectURL = 'addEdit.php';
$title = $_POST['title'];
$id = $_POST['id'];
$galData = array(
'title' => $title
);
$sessData['postData'] = $galData;
$sessData['postData']['id'] = $id;
$idStr = !empty($id)?'?id='.$id:'';
if(empty($title)){
$error = '<br/>Enter the gallery title.';
}
if(!empty($error)){
$statusMsg = 'Please fill all the mandatory fields.'.$error;
}else{
if(!empty($id)){
$condition = array('id' => $id);
$update = $db->update($galData, $condition);
$galleryID = $id;
}else{
$insert = $db->insert($galData);
$galleryID = $insert;
}
$fileImages = array_filter($_FILES['images']['name']);
if(!empty($galleryID)){
if(!empty($fileImages)){
foreach($fileImages as $key=>$val){
$fileName = $galleryID.'_'.basename($fileImages[$key]);
$targetFilePath = $uploadDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
if(move_uploaded_file($_FILES["images"]["tmp_name"][$key], $targetFilePath)){
$imgData = array(
'gallery_id' => $galleryID,
'file_name' => $fileName
);
$insert = $db->insertImage($imgData);
}else{
$errorUpload .= $fileImages[$key].' | ';
}
}else{
$errorUploadType .= $fileImages[$key].' | ';
}
}
$errorUpload = !empty($errorUpload)?'Upload Error: '.trim($errorUpload, ' | '):'';
$errorUploadType = !empty($errorUploadType)?'File Type Error: '.trim($errorUploadType, ' | '):'';
$errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType;
}
$statusType = 'success';
$statusMsg = 'Gallery images has been uploaded successfully.'.$errorMsg;
$sessData['postData'] = '';
$redirectURL = 'index.php';
}else{
$statusMsg = 'Some problem occurred, please try again.';
$redirectURL .= $idStr;
}
}
$sessData['status']['type'] = $statusType;
$sessData['status']['msg'] = $statusMsg;
}elseif(($_REQUEST['action_type'] == 'block') && !empty($_GET['id'])){
$galData = array('status' => 0);
$condition = array('id' => $_GET['id']);
$update = $db->update($galData, $condition);
if($update){
$statusType = 'success';
$statusMsg = 'Gallery data has been blocked successfully.';
}else{
$statusMsg = 'Some problem occurred, please try again.';
}
$sessData['status']['type'] = $statusType;
$sessData['status']['msg'] = $statusMsg;
}elseif(($_REQUEST['action_type'] == 'unblock') && !empty($_GET['id'])){
$galData = array('status' => 1);
$condition = array('id' => $_GET['id']);
$update = $db->update($galData, $condition);
if($update){
$statusType = 'success';
$statusMsg = 'Gallery data has been activated successfully.';
}else{
$statusMsg = 'Some problem occurred, please try again.';
}
$sessData['status']['type'] = $statusType;
$sessData['status']['msg'] = $statusMsg;
}elseif(($_REQUEST['action_type'] == 'delete') && !empty($_GET['id'])){
$conditions['where'] = array(
'id' => $_GET['id'],
);
$conditions['return_type'] = 'single';
$prevData = $db->getRows($conditions);
$condition = array('id' => $_GET['id']);
$delete = $db->delete($condition);
if($delete){
$condition = array('gallery_id' => $_GET['id']);
$delete = $db->deleteImage($condition);
if(!empty($prevData['images'])){
foreach($prevData['images'] as $img){
@unlink($uploadDir.$img['file_name']);
}
}
$statusType = 'success';
$statusMsg = 'Gallery has been deleted successfully.';
}else{
$statusMsg = 'Some problem occurred, please try again.';
}
$sessData['status']['type'] = $statusType;
$sessData['status']['msg'] = $statusMsg;
}elseif(($_POST['action_type'] == 'img_delete') && !empty($_POST['id'])){
$prevData = $db->getImgRow($_POST['id']);
$condition = array('id' => $_POST['id']);
$delete = $db->deleteImage($condition);
if($delete){
@unlink($uploadDir.$prevData['file_name']);
$status = 'ok';
}else{
$status = 'err';
}
echo $status;die;
}
$_SESSION['sessData'] = $sessData;
header("Location: ".$redirectURL);
exit();
?>
view.php
<?php
if(empty($_GET['id'])){
header("Location: manage.php");
}
require_once 'DB.class.php';
$db = new DB();
$conditions['where'] = array(
'id' => $_GET['id'],
);
$conditions['return_type'] = 'single';
$galData = $db->getRows($conditions);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="row">
<div class="col-md-12">
<h5><?php echo !empty($galData['title'])?$galData['title']:''; ?></h5>
<?php if(!empty($galData['images'])){ ?>
<div class="gallery-img">
<?php foreach($galData['images'] as $imgRow){ ?>
<div class="img-box" id="imgb_<?php echo $imgRow['id']; ?>">
<img src="uploads/images/<?php echo $imgRow['file_name']; ?>">
<a href="javascript:void(0);" class="badge badge-danger" onclick="deleteImage('<?php echo $imgRow['id']; ?>')">delete</a>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
<a href="index.php" class="btn btn-primary">Back to List</a>
</div>
</body>
</html>
Now you can check your own.
Output :
- How To Use Php Conditional Statement Example
- How to Check if String Contains Regex in PHP?
- PHP Array_column() Function Example
- PHP Generate List of Random Numbers Between 0 and 100 Example
- How to User Login with Facebook in PHP?
- How to Explode Every Character into Array Using PHP Example?
- PHP Form Validation Tutorial
- PHP Convert XML to JSON Example