dppb79372 2014-05-20 12:29
浏览 37
已采纳

MySql - 替换“array”-value

I have records like "1,3,6,17" in a column and use the following to delete e.g. "6" from them:

$sql = "SELECT SeId, SeCatId FROM series WHERE FIND_IN_SET(:catid,SeCatId)";
$stmt = $dbh->prepare($sql);
$stmt -> bindParam('catid',$id);
$stmt->execute();
$result = $stmt->FetchAll();
foreach($result as $row){
  $seid = $row['SeId'];
  $ids = explode(",",$row['SeCatId']);
  $i = 0;
  foreach($ids as $catid) {
    if($catid===$id){unset($ids[$i]);}
    $i++;
  }
  $ids = implode(",",$ids);
  $sql = "UPDATE series SET SeCatId = :catid WHERE SeId = :id";
  $stmt = $dbh->prepare($sql);
  $stmt -> bindParam(':catid',$ids);
  $stmt -> bindParam(':id',$seid);
  $stmt->execute();
}

Works fine, but seems to be complicated. Is there an easier way to do the same?

  • 写回答

4条回答 默认 最新

  • doumeilmikv7099 2014-05-20 12:38
    关注

    You can use array_diff and do something like

    $stmt->bindParam(':catid', implode(',', array_diff(explode(",", $row['SeCatId']), array('6')));
    

    But your problem is not PHP but your SQL schema. You should not have "array" value inside a same field (read database normalization to know why). Normalization is here to avoid such problems. You should have a separate schema having SeId and SeCatId as column, SeId being a foreign key to your series table and SeCatId is a unique integer (not an array).

    You should have rows like:

    SeId | SeCatId
    1    | 1
    1    | 3
    1    | 6
    1    | 7
    

    And then deleting one category is only a matter of simple DELETE statement.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)