这是我的解决方案,您将数据放入单个数组中,并自动复制/填充到“INSERT INTO .. ON DUPLICATE UPDATE ..”查询中。
它对可维护性很有帮助,如果你愿意,你也可以把它变成一个函数/方法。
// save to db:
$qData = [
"id" => mysql_real_escape_string($email_id),
"synd_id" => mysql_real_escape_string($synd_id),
"campaign_id" => mysql_real_escape_string($campaign_id),
"event_id" => mysql_real_escape_string($event_id),
"user_id" => mysql_real_escape_string($user_id),
"campaign_name" => mysql_real_escape_string($campaign_name),
"subject" => mysql_real_escape_string($subject),
"from_name"=> mysql_real_escape_string($from_name),
"from_email"=> mysql_real_escape_string($from),
"content"=> mysql_real_escape_string($html),
"link_to_template" => mysql_real_escape_string($hash),
"ext_campaign_id" => mysql_real_escape_string($ext_campaign_id),
"ext_list_id"=> mysql_real_escape_string($ext_list_id),
];
$q = "INSERT INTO email_campaigns (".
// i.e create a string like `id`, `synd_id`, `campaign_id`.. with linebreaks for readability
implode(", \n", array_map(function($k){ return "`$k`"; }, array_keys($qData)))
.")
VALUES (".
// i.e '20', '532', '600' ..
implode(", \n", array_map(function($v){ return "'$v'"; }, array_values($qData)))
." ) ON DUPLICATE KEY UPDATE ".
// i.e `synd_id`='532', `campaign_id`='600' ...
// id & link_to_template table keys are excluded based on the array below
implode(", \n", array_filter(array_map(function($k, $v){ if(!in_array($k, ['id', 'link_to_template']) ) return "`$k`='$v'" ; }, array_keys($qData), array_values($qData)))) ;