2012-09-20 287 views
1

請參閱下面的代碼,它檢查數據是否存在於表中,如果不存在,則插入它或者更新表。檢查插入或更新表

正如你可以看到它看起來有點混亂 - 有無論如何改善代碼邏輯或更小的東西?我有幾張桌子需要做同樣的事情。

foreach ($sheet as $data) { 
    // Get Phone ID 
    $dataPhoneID = mysql_escape_string($data['handset']['phone_id']); 

    if (isset($stocks[$dataPhoneID])) { 
     $stockPhone = $stocks[$dataPhoneID ]; 
     $phoneName = mysql_escape_string($stockPhone['description']); 
     $stock = mysql_escape_string($stockPhone['stock']); 

     $SQL = "SELECT * FROM phone_affiliate WHERE affiliate_id = 1 AND affiliate_phone_id = '$dataPhoneID'"; 
     $q = mysql_query($SQL); 
     if (mysql_num_rows($q) == 0) { 
      $SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')"; 
      if (mysql_query($SQLInsert)) { 
       $phone_id = mysql_insert_id(); 
       $SQLInsert = "INSERT INTO phone_affiliate (phone_id, affiliate_id, affiliate_phone_id, stock) "; 
       $SQLInsert .= "VALUE('$phone_id', '1', '$dataPhoneID', '$stock')"; 
       mysql_query($SQLInsert) or die(mysql_error()); 
      } 
     } else { 
      $row = mysql_fetch_assoc($q); 
      $phone_id = $row['phone_id']; 
      $SQLUpdate = "UPDATE phone_affiliate set stock = '$stock' WHERE affiliate_id = 1 AND phone_id = $phone_id"; 
      mysql_query($SQLUpdate) or die(mysql_error()); 
     } 

     // Similar code block above for other tables. 
    } 
} 

注意:我知道PDO,但我沒有時間在現有系統上替換它。

+0

'mysql_escape_string'?至少使用'mysql_real_escape_string'(本身已被棄用....)使用PDO或mysqli,沒有其他選擇。而且,依靠已棄用的功能意味着,後來頭痛。 – itachi

回答

5

使用mysql的REPLACE INTOINSERT... ON DUPLICATE KEY UPDATE。例如:

foreach ($sheet as $data) { 
    // Get Phone ID 
    $dataPhoneID = mysql_escape_string($data['handset']['phone_id']); 

    if (isset($stocks[$dataPhoneID])) { 
     $stockPhone = $stocks[$dataPhoneID ]; 
     $phoneName = mysql_escape_string($stockPhone['description']); 
     $stock = mysql_escape_string($stockPhone['stock']); 

     $SQLInsert = "INSERT INTO phone_affiliate (affiliate_id, affiliate_phone_id, stock) "; 
     $SQLInsert .= "VALUES ('1', '$dataPhoneID', '$stock') "; 
     $SQLInsert .= "ON DUPLICATE KEY UPDATE stock = '$stock'"; 
     mysql_query($SQLInsert); 
     if (mysql_insert_id()) { 
      $SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')"; 
      mysql_query($SQLInsert); 
      $phone_id = mysql_insert_id(); 
      $SQLUpdate = "UPDATE phone_affiliate set phone_id = $phone_id WHERE affiliate_id = 1 AND affiliate_phone_id = $dataPhoneID_id"; 
     } 
    } 
} 
+0

請從我的代碼示例中顯示實例。 –

+0

嘗試用這些語句重寫您的示例,但我對您的模型不夠了解,例如唯一的鍵,以及爲什麼如果phone_affiliate中沒有記錄,您總是插入到手機中。 –

+0

如果'phone_affiliate'中不存在數據,那麼它將在'phone'和'phone_affiliate'表中插入一條記錄。如果記錄已經存在於'phone_affiliate'中,那麼就更新它。你明白嗎? –

0

您也可以使用INSERT IGNORE建設