Deleting Multiple Records via Checkboxes and related (e.g. image) files

This tutorial is now available as an extension

What this is about

Some time ago I wrote my first tutorial on how to delete multiple records in a database, after selecting them by means of a checkbox.

I was glad to discover that a good number of UD users shared the need to delete selected records in one go, rather than one by one. Now, based on user feedback, I would like to take this function one step further.

This is about deleting not only selected records in a database, but related files as well.  Typically, this is the case when your database contains links to image files that have been uploaded. Deleting records containing paths to these files does not eliminate the files themselves.

This tutorial starts where the previous one left you. So it still expects input from a delete selection page (Sel.asp).. This page displays a list of records next to a checkbox enabling the selection of which records to delete. So you can create the page following the instructions from the previous tutorial..

What you need

First of all you need to have read the previous tutorial.  This example uses the same names; it just expects the database table (PressReleases) to have one additional field, called Path. As the name implies, this field contains the relative path (e.g. images/butterfly.jpg) to an image file.

Here's the code

<%@ language=VBScript %>
<% Option Explicit %>
<%

Dim strID,RS,File,sql

strID=Request("checkbox")

 

Set File = CreateObject("Scripting.FileSystemObject")

 

Set RS = Server.CreateObject("ADODB.Recordset")

RS.ActiveConnection = "dsn=Multidelete;"

 

sql="SELECT * FROM PressReleases WHERE ID IN "
sql=sql &"(" & strID & ")"

 

RS.Source = sql
RS.CursorType = 0
RS.CursorLocation = 2
RS.LockType = 3
RS.Open

While RS.EOF=False
File.DeleteFile(Server.Mappath(RS("Path")))
RS.Delete
RS.MoveNext
Wend


RS.Close
Set File=Nothing
Set RS=Nothing
Response.Redirect "Sel.asp"

%>

Comment

 



Define 4 variables,

load the value passed by the string (for the checkbox field)into one variable

create an instance of the FileSystemObject called File


create a recordset called RS

create a connection using dsn (Multidelete)


assemble a SQL command, making a selection based on the existence of ID fields in an external table


apply the SQL command to the recordset

 

open the recordset and loop through it, first deleting the associated file and
then the record itself. The Server Mappath function converts a virtual path into a physical one, which is necessary for deleting files.

 

redirect to the selection file ("Sel.asp")

 

Back to the old tutorial

Sorry, but I am no longer able to provide any support to this tutorial. Please take it as is.