delete image from folder in php and MySQL Database

Ajax JavaScript jQuery Laravel Mysql Mysqli php

Hi, today We are going to tell you about delete image from folder in php how to remove the file or picture from folder as well as MySQL database Table using php script, many developers they are not care to delete a picture or file while deleting a records from database they keep the files related to records and it will effects on server storage, we will find many solutions to remove files from directory We will give you a simple process let’s display how we do this.

List of all Google Adsense, VueJS, AngularJS, PHP, Laravel Examples.

As a PHP beginner step by step, remove file from folder as well as database can be very hard. Because it required Two types of the processes. First of all is remove file from directory. Second is delete database record having that file path.

PHP Remove File from Folder and Database

Developer often confused which process comes starting. few delete database record initial and then remove/delete file from directory as well as many remove/delete file primary and then delete database record. Therefor which practice is correct?

Best solutions is to remove/delete file from directory first(delete uploaded file php) and then delete MySQL database table record by php delete image on click. In this tutorial We are going to Display you php unlink image from folder with how to do that.

delete image from folder in php
jQuery AJAX Add Delete Multiple Image Upload

Create Database:

here simple step to DB connect this file to mysql database as well as get or fetch the records from gallery DB table bellow We are just getting single record only if you want you can retrieve all Database records and keep it in while loop, now We are just location the image tag as well take the src anchor tag for delete button as well as location the do_file_delete.php file in href with We just pass arguments the gallery id to customproductid variable

Create database demo;

Create Database Table:

CREATE TABLE `galleries` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`image` VARCHAR(255) NOT NULL,
`created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
success KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=10
;

Database Connection and Select Images Query:


$conn = mysqli_connect('localhost','root','','gallery_demo');

	if(!$conn)
	{
		die(mysqli_error());
	}
	
	
	$sql = "select * from galleries";
	$rs = mysqli_query($conn, $sql);


Display Images from Database:

<div class="container">
		<h3 class="text-center">Delete Images</h3>
		
		<div class="row">

<?php 
		while($row = mysqli_fetch_assoc($rs))
		{
			$galleryImgPathW = "uploads/".$row['image'];
		?>	
			
				
			<div class="col-md-12 text-center" style="margin-top:10px">
				<img src="<?php echo $galleryImgPathW ?>" width="200">
				<a href="?deleteid=<?php echo $row["id"]?>" class="btn btn-primary">Delete</a>
			</div>
			
			
	<?php		
		}
		
	?>
	</div>
	</div>


</div>
</div>

Success and Error Messages:


<?php 
		if(isset($displayErrMessage))
		{
		?>
			<div class="alert alert-danger">
				<?php 
					echo $displayErrMessage;
					unset($displayErrMessage);
				?>
			</div>
		<?php 
		}
		?>
		
		<?php 
		if(isset($_GET['success']) && $_GET['success'] == 'true')
		{
		?>
			<div class="alert alert-success">
				<?php 
					echo "Images has been deleted sucessfully";
				?>
			</div>
		<?php 
		}
		?>


Remove/delete Image Code:

here connect this file to database, now retrieve the image from gallery table by using where query condition and assign the $del variable to galleryid, now use unlink() method to remove/delete the files or pictures from folder unlink(“medias/$fetchImgTitleName”); inside the function just give the directory path and file name to remove/delete after the function write the query to delete the gallery record with delete previous image from directory when updated by new image in php also you can read my previous post Like as how to delete image from folder in php codeigniter


<?php 
if(isset($_GET['deleteid']))
	{
		$querySelect = "select * from galleries where id = ".$_GET['deleteid'];
		$ResultSelectStmt = mysqli_query($conn,$querySelect);
		$fetchRecords = mysqli_fetch_assoc($ResultSelectStmt);
		
		$fetchImgTitleName = $fetchRecords['image'];
		
		$createDeletePath = "uploads/".$fetchImgTitleName;
		
		if(unlink($createDeletePath))
		{
			$liveSqlQQ = "delete from galleries where id = ".$fetchRecords['id'];
			$rsDelete = mysqli_query($conn, $liveSqlQQ);	
			
			if($rsDelete)
			{
				header('location:index.php?success=true');
				exit();
			}
		}
		else
		{
			$displayErrMessage = "Unable to delete Image";
		}
		
	}
?>


Complete Code : delete image from database and folder in php

delete file from folder in php


<?php 
	
	$conn = mysqli_connect('localhost','root','','galleries_demo');

	if(!$conn)
	{
		die(mysqli_error());
	}
	
	
	$sql = "select * from galleries";
	$rs = mysqli_query($conn, $sql);
	
	
	if(isset($_GET['deleteid']))
	{
		$querySelect = "select * from galleries where id = ".$_GET['deleteid'];
		$ResultSelectStmt = mysqli_query($conn,$querySelect);
		$fetchRecords = mysqli_fetch_assoc($ResultSelectStmt);
		
		$fetchImgTitleName = $fetchRecords['image'];
		
		$createDeletePath = "uploads/".$fetchImgTitleName;
		
		if(unlink($createDeletePath))
		{
			$liveSqlQQ = "delete from galleries where id = ".$fetchRecords['id'];
			$rsDelete = mysqli_query($conn, $liveSqlQQ);	
			
			if($rsDelete)
			{
				header('location:index.php?success=true');
				exit();
			}
		}
		else
		{
			$displayErrMessage = "Sorry, Unable to delete Image";
		}
		
	}

	
?>

<!DOCTYPE html>
<html>
<head>
<title>PHP remove uploaded file from folder and database - www.pakainfo.com</title>


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


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" >
</head>

<body>
	<div class="container">
		<h3 class="text-center">Delete gallery Images</h3>
		
		<div class="row">
		
		<?php 
		if(isset($displayErrMessage))
		{
		?>
			<div class="alert alert-danger">
				<?php 
					echo $displayErrMessage;
					unset($displayErrMessage);
				?>
			</div>
		<?php 
		}
		?>
		
		<?php 
		if(isset($_GET['success']) && $_GET['success'] == 'true')
		{
		?>
			<div class="alert alert-success">
				<?php 
					echo "Images has been deleted sucessfully";
				?>
			</div>
		<?php 
		}
		?>
		
		
	<?php 
		while($row = mysqli_fetch_assoc($rs))
		{
			$galleryImgPathW = "uploads/".$row['image'];
		?>	
			
				
			<div class="col-md-12 text-center" style="margin-top:10px">
				<img src="<?php echo $galleryImgPathW ?>" width="200">
				<a href="?deleteid=<?php echo $row["id"]?>" class="btn btn-primary">Delete</a>
			</div>
			
			
	<?php		
		}
		
	?>
	</div>
	</div>
	
	
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>	
</body>
</html>


Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about delete image from folder in php.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   laravel resource controller edit Not Working
  2.   Basic OOP PHP CRUD Operation Using MySQLi from Scratch
  3.   Eloquent ORM Soft Delete in Laravel 6
  4.   PHP Remove File from Folder and Database
  5.   How to count files in a directory using PHP Laravel?
  6.   Custom Helper Functions in Laravel 6 Example
  7.   PHP addslashes Function with Examples
  8.   crud with php oop and mvc design pattern
  9.   PHP Laravel Sorting collection SortBy
  10.   Vue Shopping Cart - VueJS Shopping Cart - vue js e-commerce

Leave a Reply

Your email address will not be published. Required fields are marked *