2013-03-05 113 views
0

我需要一些關於粘性情況的幫助。使用PHP將基於其他值的值插入MYSQL

目前,我有一個數組,看起來像這樣

Array 
(
[0] => Array 
    (
     [Task_ID] => 59 
     [email] => [email protected] 
    ) 

[1] => Array 
    (
     [Task_ID] => 59 
     [email] => [email protected] 
    ) 

[2] => Array 
    (
     [Task_ID] => 59 
     [email] => [email protected] 
    ) 

[3] => Array 
    (
     [Task_ID] => 60 
     [email] => [email protected] 
    ) 

[4] => Array 
    (
     [Task_ID] => 60 
     [email] => [email protected] 
    ) 

[5] => Array 
    (
     [Task_ID] => 61 
     [email] => [email protected] 
    ) 

) 

這是我目前的INSERT語句。

 if(is_array($myArr)){ 
     $valuesArr = array(); 
     foreach($myArr as $row){ 

      $sql = "INSERT INTO user_data (Task_ID, email, url) values "; 
      $TaskID = (int) $row['Task_ID']; 
      $email = mysql_real_escape_string($row['email']); 

      $valuesArr[] = "('$TaskID', '$email')"; 
      $sql .= "('$TaskID', '$email')"; 
      mysql_query($sql) or exit(mysql_error()); 
     } 
    } 

我想要做的是插入一個新值,它不是數組中的URL值。

對於URL,我想用每個唯一的電子郵件增加一個數字,其中相同的電子郵件將獲得相同的URL值。

SQL語法應該是什麼樣子的例子。

INSERT INTO user_data (TaskID, email, url) values ('60', '[email protected]','1') 
INSERT INTO user_data (TaskID, email, url) values ('80', '[email protected]','1') 
INSERT INTO user_data (TaskID, email, url) values ('82', '[email protected]','2') 
INSERT INTO user_data (TaskID, email, url) values ('62', '[email protected]','2') 
INSERT INTO user_data (TaskID, email, url) values ('42', '[email protected]','2') 
INSERT INTO user_data (TaskID, email, url) values ('61', '[email protected]','3') 
INSERT INTO user_data (TaskID, email, url) values ('81', '[email protected]','3') 
INSERT INTO user_data (TaskID, email, url) values ('92', '[email protected]','4') 
INSERT INTO user_data (TaskID, email, url) values ('32', '[email protected]','4') 
INSERT INTO user_data (TaskID, email, url) values ('72', '[email protected]','4') 

注意每個電子郵件更改的URL增加1。請注意,TaskID不是PK,電子郵件也不是按順序排列的。

非常感謝您的閱讀讚賞。

回答

1

試試看

if (is_array($myArr)) { 
    $valuesArr = array(); 
    $addedEmails = array(); 

    $cnt = 0; 
    foreach($myArr as $row){ 

     $sql = "INSERT INTO user_data (Task_ID, email, url) values "; 
     $TaskID = (int) $row['Task_ID']; 
     $email = mysql_real_escape_string($row['email']); 

     if (!in_array($email, $addedEmails)) { 
      $cnt++; 
      $addedEmails[] = $email; 
     } 

     $valuesArr[] = "('$TaskID', '$email', '$cnt')"; 
     $sql .= "('$TaskID', '$email', '$cnt')"; 
     mysql_query($sql) or exit(mysql_error()); 
    } 
}