2017-01-03 112 views
0

我的最終目標是在插入新促銷後,使用新PK ID更新Dealers表中的現有列(promo_ids)。我想保留已設置的現有ID。這可能嗎?如果是這樣,任何正確的方向將是偉大的。我對SQL語句還很陌生。以下是我目前必須添加新促銷的代碼。插入SQL後更新

public function add_new_promo() { 
     global $wpdb; 

     $result = $wpdb->query(
        $wpdb->prepare(
        " 
        INSERT INTO $wpdb->gdp_promos 
        (promo, short_desc, long_desc, rebate_url, legal_copy, image_id, promo_headline, promo_line1, promo_desc, linkback_url, share_image_id, dealer_ids) 
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) 
        ", 
        $this->promo_data['promo'], 
        $this->promo_data['short_desc'], 
        $this->promo_data['long_desc'], 
        $this->promo_data['rebate_url'], 
        $this->promo_data['legal_copy'], 
        $this->promo_data['image_id'], 
        $this->promo_data['promo_line1'], 
        $this->promo_data['promo_headline'], 
        $this->promo_data['promo_desc'], 
        $this->promo_data['linkback_url'], 
        $this->promo_data['share_image_id'], 
        $this->promo_data['dealer_ids'] 
       ) 
       ); 
     if ($result === false) { 
      $state = 'error'; 
      $msg = __('There was a problem saving the new promo details, please try again.', 'gdp'); 
     } else { 
      $_POST = array(); 
      $state = 'updated'; 
      $msg = __("promo {$this->promo_data['promo']} successfully added.", 'gdp'); 
     } 
     add_settings_error ('add-promo', esc_attr('add-promo'), $msg, $state); 
    } 

回答

0

是它是通過或者通過在存儲過程中在一個事務塊包裹兩者insertupdate語句中使用AFTER INSERT TRIGGERPromotion表(OR)。如果ID列是AUTO_INCREMENT列,您可以使用LAST_INSERT_ID()獲取新插入的PK ID列值。

請參閱MySQL文檔以瞭解更多信息。

0

在你else塊,添加:

$new_pk_id = $wpdb->insert_id; 
$update_stmt = "UPDATE Dealers SET promos_id = %d WHERE dealer_id = %d"; 
$wpdb->query($wpdb->prepare($update_stmt, array($new_pk_id, $specific_dealer_id)); 
+0

這看起來像同時刪除所有現有的促銷標識它將更新在經銷商處的表每一位經銷商用新的推廣ID。 –

+0

你說得對。抱歉。我編輯過它。 –