从mysql php删除批量不工作

时间:2017-09-18 23:10:36

标签: php mysql

我需要使用pdo对象

从mysql php中删除批量

我有这样的数组

 $emails= array();
  foreach ($items_emails as $datav) {

 $emails[] = $datav[5];
}

然后我尝试使用pdo对象从数组参数

中删除mysql
$sql = "DELETE FROM ".$data_table." WHERE email_address = :email_address";   
     $stmt = $db_datas->prepare($sql);
 $stmt->execute(array(':email_address' => $emails)); 

我收到此错误

完全在此语句中的数组到字符串转换

 $stmt->execute(array(':email_address' => $emails)); 

1 个答案:

答案 0 :(得分:1)

"DELETE FROM x WHERE y = z"语法只接受单个值进行比较,这就是传递数组失败的原因。您可以循环遍历值数组并单独删除条目,如下所示:

$sql = "DELETE FROM ".$data_table." WHERE email_address = :email_address";   
$stmt = $db_datas->prepare($sql);

foreach ($emails as $email) {
    $stmt->execute(array(':email_address' => $email)); 
}

或者,使用WHERE x IN (list)将其转换为单个查询:

$numberOfPlaceholders = count($emails);
$placeholdersArray = str_split(str_repeat('?', $numberOfPlaceholders));
$placeholders = implode(',', $placeholdersArray);
$sql = "DELETE FROM $data_table WHERE email_address IN ($placeholders)";
$stmt = $db_datas->prepare($sql);
$stmt->execute($emails);

您需要为列表中的每个元素创建一个单独的占位符,以便能够按照注释中的指示传递数组!