AlwaysStudent
AlwaysStudent

Reputation: 1374

Remove the desired number from data

I have a question about how can I delete the desired number from the img_ids. As you see in the table below the img_ids like 68,67,66,65,64, . I want to delete for example number 67, how can I do that with PHP. My mind is confused because of the commas :S.

enter image description here

<div class="delete" id="67">Delete Image</div>

Ajax

$("body").on("click", ".delete", function(){
  var deleteimgid = $(this).attr("id");
  var data = 'img='+deleteimgid;
$.ajax({
   type: 'POST',
   url: 'delete.php',
   data: data,
   cache: false,
   beforeSend: function(){},
   success: function(response){

   }
});
});

delete.php

<?php 
    include_once 'inc.php';

    if(isset($_POST['img'])){
       $imgid = mysqli_real_escape_string($db, $imgid);

      // Then what should be the query ? 
      // I am confused because of the commas.
    }
?>

Upvotes: 0

Views: 52

Answers (1)

Manuel Mannhardt
Manuel Mannhardt

Reputation: 2201

Even tho you should not store data like that, here a working approach:

$imgList = '12,23,45,56,67,78';
$imgid = 12;

$imgIds = explode(',', $imgList);
$imgIds = array_filter($imgIds, function ($item) use ($imgid) {
    return $imgid != $item;
});

$imgList = implode(',', $imgIds);
print $ImgList; // prints 23,45,56,67,78

What it does:

  1. Splitting the list of ids into an array by comma
  2. Use array_filter to map over the array and remove the desired value
  3. Implode the list again by comma

How you actually should/could store your data

As others have pointed out in the comments, you should normalize your database. Read more

You also could use a blob field instead of a text field, since PHP can handle blob data very easy using serialize/unserialize

Upvotes: 4

Related Questions