0

I have created an image gallery using the PHP code below, which will retrieve the images from a database. Now I want to add a delete symbol to the images so that I can delete it after getting retrieved from the database. Kindly help me out. How can i do this?

<div class="header">
    <h2>
        GALLERY
        <!--<small>All pictures taken from <a href="https://unsplash.com/" target="_blank">unsplash.com</a></small>-->
    </h2>
    <hr/>
    <div class="body">
        <div id="aniimated-thumbnials" class="list-unstyled row clearfix">
            <?php
            //Include database configuration file
            include('dbConfig.php');

            //get images from database
            $query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC");

            if($query->num_rows > 0){
                while($row = $query->fetch_assoc()){
                    $imageThumbURL = 'images/thumb/'.$row["file_name"];
                    $imageURL = 'images/'.$row["file_name"];
                    ?>
                    <a href="<?php echo $imageURL; ?>"  data-fancybox="group" data-caption="<?php echo $row["title"]; ?>" >
                       <img src="<?php echo $imageThumbURL; ?>" alt="" />
                    </a>
                <?php }
            } ?>
        </div>
    </div>
</div>
NikuNj Rathod
  • 1,663
  • 1
  • 17
  • 26
Shaik
  • 286
  • 2
  • 15
  • 36

3 Answers3

1

you can add a delete button simply like

<?php
    //Include database configuration file
    include('dbConfig.php');

    //get images from database
    $query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC");

    if($query->num_rows > 0){
        while($row = $query->fetch_assoc()){
            $imageThumbURL = 'images/thumb/'.$row["file_name"];
            $imageURL = 'images/'.$row["file_name"];
?>
            <a id="imageid-<?=$row[0]?>" href="<?php echo $imageURL; ?>"  data-fancybox="group" data-caption="<?php echo $row["title"]; ?>" >
               <img src="<?php echo $imageThumbURL; ?>" alt="" />
               <div class="delete" data-imgId="<?=$row[0]?>">Delete</div>
            </a>
<?php 
        }
    } 
?>

then handle the click of that button and an ajax call like

$(".delete").click(function(e){
    var rowId = e.target.dataset.imgId;
    $.ajax({
        method: 'DELETE',
        url: "", // url to delete
        data: {image_id: rowId}
        success: function(){
          $('imageid-'+rowId).hide();
        }
    });
});

here it will pass the image id as a parameter to the api call, and will hide the image once the api call is success.

Aswin Ramesh
  • 1,654
  • 1
  • 13
  • 13
0
      if($query->num_rows > 0) {
        while($row = $query->fetch_assoc()) {
          $imageThumbURL = 'images/thumb/'.$row["file_name"];
          $imageURL = 'images/'.$row["file_name"];
      ?>
      <a href="<?php echo $imageURL; ?>"  data-fancybox="group" data-caption="<?php echo $row["title"]; ?>" >
        <img src="<?php echo $imageThumbURL; ?>" alt="" /></a>
      <!-- HERE YOU CREATE SPAN AND GIVE IMAGE ID AS DATA ID
      <span class="deleteImage" data-id="<?=$row[0]?>">Delete Image</span>
      <?php }

And Ajax Call is As follow

$(".deleteImage").click(function(){
    $.ajax({
        //PAGE THAT DELETE IMAGE
        url: "delete_image_page.php",
        context: document.body,
        data: {data:data}
        success: function(){
          //ON SUCCESS WHAT YOU WANT TO DO
          $(this).addClass("done");
        }
    });
});

NOTE: For more information read this Documentation. And you should have to readthis post before asking this type of question.

TarangP
  • 2,711
  • 5
  • 20
  • 41
0

This is a small example. Basically, on a click of a button you would call an AJAX method to send the image name you want deleted. The request needs to be sent to another PHP file that will receive the request, process it, and return a response. Based on the response we get we will know if the method was successful.

You need an additional Javascript file to hold the AJAX function, and a additional PHP file to handle the request and return a response.

Your PHP file:

<div class="header">
<h2>GALLERY</h2>
<!--<small>All pictures taken from <a href="https://unsplash.com/" target="_blank">unsplash.com</a></small>-->

<hr/>
<div class="body">
<div id="aniimated-thumbnials" class="list-unstyled row clearfix">

<?php
  //Include database configuration file
  include('dbConfig.php');

  //get images from database
  $query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC");

  if($query->num_rows > 0)
  {
    while($row = $query->fetch_assoc())
    {
      $imageThumbURL = 'images/thumb/'.$row["file_name"];
      $imageURL = 'images/'.$row["file_name"];

      echo '<div class="imageContainer">
                <a href="'.$imageURL.'"  data-fancybox="group" data-caption="'.$row['title'].'" >
                    <img src="'.$imageThumbURL.'" alt="" />
                </a>
                <input type="button" onclick="deleteImage(\''.$row["file_name"].'\')" value="Delete" />
            </div>';
    }
  }   
?>

            </div>
        </div>
    </div>

The Javascript file:

// Send the `fileName` of the image
function deleteImage(fileName)
{
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function()
  {
    // This `if` underneath is success. It means we got a response back
    if (this.readyState == 4 && this.status == 200)
    {
      if(this.responseText == "OK")  
      {
          alert('Success, deleted: ' + fileName + ' Response: ' + this.responseText);
      }
      else if(this.responseText == "Not OK") 
      {
          alert('Picture: ' + fileName + ' was  not deleted.');
      }
  }
};
// For example you send a request to deleteImage.php sending `fileName` info
// - deleteImage.php just needs to echo the response to answer back
xhttp.open("GET", "deleteImage.php?fileName=" + fileName, true);
xhttp.send();

}

The other PHP file, deleteImage.php (the AJAX request receiver):

 <?php
     $con = ... // Here goes DB connection data

     if(isset($_GET['fileName']) && $_GET['fileName'] != '')
     {
          // Clean the input
          $clean['fileName'] = mysqli_real_escape_string($con, $_GET['fileName']);
          // Do something
     }

     // if successful echo 'OK';
     // if not successful echo 'Not OK';
 ?>
Ivan86
  • 5,695
  • 2
  • 14
  • 30