Delete A SQL Row and A File Using PHP

PHP

You can use this PHP and MySqli code to delete a specific row from your database and a specific file from your server.

In this example I have a website where users can upload and share photos, as part of the user experience they can delete their own files. If the file was uploaded when they wern’t logged in, then the image was uploaded “anonymously” and needs to be requested to be deleted.

The script I put together has a html form, this is where I can type the image id, which is also the row id. It then uses PHP and MySqli to query the database and get the path to the image in my folder structure, it then deletes the image before deleting the row in the database.

This will save you a ton of time, especially if you are having to delete everything manually.

Here Is the Script

 <?php if(isset($_POST['delimg'])){
        $delid = $_POST['delid'];

        echo"Image Deleted<BR>";

        $iuser = mysqli_query($connect, "SELECT * FROM `images` WHERE id='$delid' LIMIT 1");
        $rowi = mysqli_fetch_assoc($iuser);
        $imgpath = $rowi['imagepath'];
unlink($imgpath) or die("Couldn't delete file");

        $delq = mysqli_query($connect, "DELETE FROM images WHERE id='$delid'");

    } ?>

    <form method="POST" action="">
        <input type="number" name="delid" value="0">
        <input type="submit" name="delimg" value="Delete Image">
    </form>

Feel free to use this code and if you found it helpful then leave a comment below.

Leave a Reply

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