我有一个需要传递的项目列表,应该删除。我怎么能用PHP做到这一点?
$query = "DELETE from members WHERE member_id ='$chan[2]' ";
$chan[2]
包含多个值,但只删除一个。
答案 0 :(得分:10)
$ chan [2]指的是$ chan数组中的一个元素。所以,我认为你的意思是$ chan有多个值。
试试这个:
$query = "DELETE FROM members WHERE member_id IN (" . implode(", ", $chan) . ");";
答案 1 :(得分:3)
使用
$query = "DELETE FROM members WHERE member_id IN (" . join("," $chan[2]) . ")";
如果$chan[2]
包含要删除的ID列表。还要确保只将数值传递给查询以避免SQL注入问题。
答案 2 :(得分:0)
$member_ids = implode(", ", $chan);
"$query = "DELETE from members WHERE member_id IN ($member_ids)";
答案 3 :(得分:0)
等于运算符将仅删除与给定值完全匹配的值。如果数组中有多个ID,则需要使用其他条件。您可以使用MYSQL函数FIND_IN_SET()
,例如,如果这是您的数据库:
$ids = array(1, 2, 3);
$query = "DELETE FROM members WHERE FIND_IN_SET(member_id, '" . implode(',', $ids) . "')";
还有一件事:如果您收到了用户的ID,请非常小心。 It might contain bogus data。使用mysql_escape_string()
完成清理:
$ids = array_map('mysql_escape_string', $ids);
答案 4 :(得分:0)
以上给出的内容是正确的方法。纯粹为了使发生的事情非常清楚;如果implode不存在,这是你使用的代码(我认为$ chan是一个二维数组,所以$ chan [2]有5个成员,否则使用$ chan)
// start roll-your-own $member_id_cond = implode(", ",$chan[2]);
$member_id_cond = "";
foreach( $chan[2] as $key => $data) {
$member_id_cond .= $data . ", ";
if($key == 4) { //this is just to remove the last comma
$member_id_cond = sub_str($member_id_cond, 0, -2);
}
}
//end implode
$query = "DELETE FROM members WHERE member_id IN ($member_id_cond)";