2015-11-02 86 views
-3

我創建了一個添加用戶按鈕,但是當同一頁面上有多個用戶時,他們都會在點擊時添加。添加朋友按鈕PHP/SQL

下面是代碼:

$ data_emails是包含用戶的電子郵件的陣列。

<?php 
    for ($i = 0; $i < count($data_emails); $i ++) { 
     echo $data_emails[$i] . ' ' . $data_usernames[$i] . '<br />'; 
     $email2 = $data_emails[$i]; 
     $contact = $data_usernames[$i]; 
     if (relationship_exists($email, $email2) === false) { 
    ?>    
    <form action="" name="add_user" method="POST"> 
    <input type="submit" name="add_user" value="Add user" /> 
    </form> 
    </div> 
    <?php 
      } 
      if (isset($_POST['add_user'])) 
      create_relationship($email, $email2, $contact);             
    } 
    ?> 
+0

爲什麼被標記爲Javascript? – Carlos2W

+3

你至少需要向我們展示你的'insertUser'函數 – WOUNDEDStevenJones

回答

0

這裏的問題是你在循環中的一切。所以它是這樣運作的。嘗試下面的代碼。

<?php 
    for ($i = 0; $i < count($data_emails); $i ++) 
    { 
     echo $data_emails[$i] . ' ' . $data_usernames[$i] . '<br />'; 
     $email2 = $data_emails[$i]; 
     $contact = $data_usernames[$i]; 
     if (relationship_exists($email, $email2) === false) 
     { 
      ?>    
      <form action="" name="add_user" method="POST"> 
       <input type="hidden" name="email" value="<?php echo $email?>"> 
       <input type="hidden" name="email2" value="<?php echo $email2?>"> 
       <input type="hidden" name="contact" value="<?php echo $contact?>"> 
       <input type="submit" name="add_user" value="Add user" /> 
      </form> 
     </div> 
    <?php 
     } 
    } 

    if (isset($_POST['add_user'])) 
    { 
     $email = mysqli_real_escape_string($conn, $_POST['add_user']); 
     $email2 = mysqli_real_escape_string($conn, $_POST['email2']); 
     $contact = mysqli_real_escape_string($conn, $_POST['contact']); 

     create_relationship($email, $email2, $contact); 
    }   
?>