插入查询执行两次或更多次

时间:2015-05-27 20:26:26

标签: php mysql

$ad = '';
$campaign = '';
$medium = '';
$source = '';
$keyword = '';
$rd = '';
$product = '';
$cbr = '';
$cpc = '';

//    
// CODE HERE THAT REPLACES ALL VARIABLES FROM BEFORE EXCEPT $cpc;
//

$cpc_q = $dbCon->prepare("SELECT * FROM dashboard_cpc WHERE campaign=:campaign");
$cpc_q->execute(array(':campaign' => $campaign));
while ($cpc_ar = $cpc_q->fetch(PDO::FETCH_ASSOC)) {
    if ($cpc_ar['only_campaign'] == 1) {
        $cpc = $cpc_ar['cpc'];
    } else {
        $cpc_second_q = $dbCon->prepare("SELECT * FROM dashboard_cpc WHERE campaign=:campaign AND ad_content=:ad");
        $cpc_second_q->execute(array(':ad' => $ad, ':campaign' => $campaign));
        $cpc_ar = $cpc_second_q->fetch(PDO::FETCH_ASSOC);
        $cpc = $cpc_ar['cpc'];
    }
}



if ($cpc != '') {
    $query = $dbCon->prepare("
        INSERT INTO visits
            (ad, campaign, medium, source, keyword, uid, date, cpc) 
        VALUES
            (:ad, :campaign, :medium, :source, :keyword, :uid, :date, :cpc)
        ");

    $query->execute(array(':ad' => $ad, ':campaign' => $campaign, ':medium' => $medium, ':source' => $source, ':keyword' => $keyword, ':uid' => $uid, ':date' => $date, ':cpc' => $cpc));
}

名为dashboard_cpc的表看起来像这样: enter image description here

没有问题:每当执行此代码时,插入会被触发几次。大多数时候它被触发两次。 唯一可以改变这一点的是:$ campaign和$ ad。对于不同的广告系列,代码会被触发不同的次数。我的同时造成这种情况吗?

inb4问:如果only_campaign等于1,则在选择cpc值时$ ad不再重要。如果它为0,那么它还应该检查$ ad。

我希望我足够清楚。

PS:我还尝试了一种SQL解决方案,但效果不佳

 $query = $dbCon->prepare("
  INSERT INTO visits
  (ad, campaign, medium, source, keyword, uid, date, cpc)
  VALUES
  (:ad, :campaign, :medium, :source, :keyword, :uid, :date,
  (SELECT
  case oc.only_campaign
  when '1' then (SELECT oc.cpc)
  when '0' then (SELECT cpc FROM dashboard_cpc WHERE ad_content =:ad)
  end as cpc
  FROM
  (SELECT * FROM dashboard_cpc WHERE campaign =:campaign) AS oc)
  )
  "); 

这里的问题是,每当我有多个具有相同名称的广告系列(所有这些广告系统的only_campaign = 0)时,上面的代码就会崩溃为" oc"临时表有多行。

由于

马吕斯S

0 个答案:

没有答案