0

I have a page that allows for multiple record deletes using checkboxes and all works fine.

However, each record may have an image associated with it stored in a folder that would also need to be deleted but I have no idea how to achieve this even though I've searched Stackoverflow and Google.

How do I delete the record(s) from the MySQL database and the image(s) associated with it from the folder?

What I have so far is:

The code that deletes the records:

if ( isset( $_POST[ 'chk_id' ] ) ) {
    $arr = $_POST[ 'chk_id' ];
    foreach ( $arr as $id ) {
        @mysqli_query( $KCC, "DELETE FROM pageContent WHERE contentID = " . $id );
    }
    $msg = "Page(s) Successfully Deleted!";
    header( "Location: delete-familyservices.php?msg=$msg" );
}

The form that selects the records to delete:

<form name="deleteRecord" id="deleteRecord" method="post" action="delete-familyservices.php">

    <?php if (isset($_GET['msg'])) { ?>
        <p class="alert alert-success">
            <?php echo $_GET['msg']; ?>
        </p>
    <?php } ?>

    <table width="100%" class="table table-striped table-bordered table-responsive">
        <tr>
            <th>Page Title</th>
            <th>Page Text</th>
            <th>Page Image</th>
            <th>Delete</th>
        </tr>

        <?php do { ?>
        <tr>
            <td width="30%" style="vertical-align: middle">
                <h4 style="text-align: left">
                    <?php echo $row_rsContent['contentTitle']; ?>
                </h4>
            </td>
            <td width="45%" style="vertical-align: middle">
                <?php echo limit_words($row_rsContent['contentData'], 10);  ?> ...</td>
            <td align="center" style="vertical-align: middle">
                <?php if (($row_rsContent['contentImage']) != null) { ?>
                <img src="../images/<?php echo $row_rsContent['contentImage']; ?>" class="img-responsive">
                <?php } else { ?> No Image
                <?php } ?>
            </td>
            <td width="5%" align="center" style="vertical-align: middle"><input type="checkbox" name="chk_id" id="chk_id" class="checkbox" value="<?php echo $row_rsContent['contentID']; ?>">
            </td>
        </tr>
        <?php } while ($row_rsContent = mysqli_fetch_assoc($rsContent));  ?>

    </table>

    <p>&nbsp;</p>

    <div class="form-group" style="text-align: center">
        <button type="submit" name="submit" id="submit" class="btn btn-success btn-lg butt">Delete Selected Page(s)</button>
        <button class="btn btn-danger btn-lg butt" type="reset">Cancel Deletion(s)</button>
    </div>
</form>

The final piece of code, which is a confirmation script:

<script type="text/javascript">
    $( document ).ready( function () {
        $( '#deleteRecord' ).submit( function ( e ) {
            if ( !confirm( "Delete the Selected Page(s)?\nThis cannot be undone." ) ) {
                e.preventDefault();
            }
        } );
    } );
</script>

I've seen the unlink() function mentioned but I don't know if this is what to use or have any idea how to incorporate it into the existing code if it is.

  • Your code is vulnerable to [**SQL injection attacks**](https://en.wikipedia.org/wiki/SQL_injection). You should use [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) prepared statements with bound parameters as described in [**this post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – Alex Howansky Apr 17 '17 at 18:31
  • [ID's Must Be Unique](http://stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same-id-if-theyre-different-eleme), specifically because it will cause problems in [JavaScript](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id) and CSS when you try to interact with those elements. – Jay Blanchard Apr 17 '17 at 18:33
  • Don't get what's your problem. You got file - then go delete it! To my recollection, PHP has got the filesystem package built-in virtually from very beginning, means, for ages. – Yuri G Apr 17 '17 at 18:40
  • @AlexHowansky. Am using mysqli (as I understand PHP will no longer be supporting mysql, I'm using mysqli, far as I know) and this page and others like this will be behind a secure login. –  Apr 17 '17 at 19:10
  • @JayBlanchard. All id's are unique. –  Apr 17 '17 at 19:11
  • The comment is not to simply use MySQLi, it's to use MySQLi prepared statements with bound parameters. If you're not doing that, then you don't **have** a secure login to be behind. – Alex Howansky Apr 17 '17 at 19:12
  • @AlexHowansky. Thanks for the heads up. I'm fairly new to using MySQL so ant help is appreciated. I'll check out the links in your first comment. –  Apr 17 '17 at 19:32

2 Answers2

0

you'll have to use the path of the image which is stored on you database like so :

unlink(' the link of the images which is fetched from db'); // correct

don't forget to check for image existence file_exists() //

lotfio
  • 1,916
  • 2
  • 18
  • 34
  • I understand it would be something like `unlink('../images/')` but I don't know where to put it within the existing code. –  Apr 17 '17 at 19:14
0

Got this from another site and a bit of trial and error.

if($_POST) {
    $arr = isset($_POST['chk_id']) ? $_POST['chk_id'] : false;
    if (is_array($arr)) {
      $filter = implode(',', $arr);
      $query = "SELECT *filename* FROM *table* WHERE *uniqueField* IN ({$filter})";
      $result = mysqli_query(*$con*, $query);
      while ($row = mysqli_fetch_object($result)) {
        $pathToImages = "*path/to/images*";
         {
            unlink("{$pathToImages}/{$row->contentImage}");
        }
      }
      // DELETE CAN BE DONE IN ONE STATEMENT
      $query = "DELETE FROM *table* WHERE *uniqueField* IN ({$filter})";
      mysqli_query(*$con*, $query);
      $msg = "Page(s) Successfully Deleted!";
      header("Location: *your-page.php*?msg=$msg");
    }
}

Thanks to everyone who contributed.

Hope this is of some help to others.