从数据中删除所需的数字

时间:2017-10-13 14:33:30

标签: php

我有一个问题,如何从img_ids删除所需的号码。正如您在下面的表格中看到的img_ids,如68,67,66,65,64,。我想删除例如数字67,我怎么能用PHP做到这一点。由于逗号,我的思绪很混乱: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.
    }
?>

1 个答案:

答案 0 :(得分:4)

即使你不应该存储这样的数据,这是一种有效的方法:

$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

它的作用:

  1. 通过逗号
  2. 将ID列表拆分为数组
  3. 使用array_filter映射数组并删除所需的值
  4. 再次使用逗号
  5. 删除列表

    您实际应该/可以存储数据的方式

    正如其他人在评论中指出的那样,您应该规范化您的数据库。 Read more

    您还可以使用blob字段而不是文本字段,因为PHP可以使用serialize / unserialize

    轻松处理blob数据