2017-07-19 90 views
0

我有MySQL數據庫具有下面的表:PHP MySQL的:添加朋友

  • 用戶表:由ID(int)和用戶名的(VARCHAR)
  • 朋友表:由ID(int)和Friends_ID(varchar)

我在我的本地主機上測試了我的腳本,它工作正常,但只要我將腳本上傳到我選擇的免費虛擬主機,它不能正常工作。例如,FriendID被添加到所有用戶的Friendlist而不是僅指定的一個。

這裏是我的PHP腳本:

<?php 
$servername= "********"; 
$serverusername="********"; 
$password="**********"; 
$dbName= "***********"; 

//Make Connection 
$connection = new mysqli($servername, $serverusername,$password, $dbName); 
//Check Connection 
if(!$connection){ 
    die("Connection Failed. ". mysqli_connect_error()); 
} 

$friend_username = 'Steven';//$_POST["friendusernamePost"]; 
$username ='Hans'; //$_POST["usernamePost"] 

$getOwnID_q = "SELECT ID FROM Users WHERE Username = '$username' "; 
$getFriendID_q = "SELECT ID FROM Users WHERE Username = '$friend_username' "; 

$ownID_result = mysqli_query($connection, $getOwnID_q); 
$ownID = mysqli_fetch_assoc($ownID_result)["ID"]; 

$friendID_result = mysqli_query($connection, $getFriendID_q); 
$friendID = mysqli_fetch_assoc($friendID_result)["ID"]; 

if($ownID<1) 
    echo "ERROR: couldn't get correct Own ID"; 
else if($friendID<1) 
    echo "ERROR: couldn't get correct friend ID"; 
else{ 
    $getFriendlist_q= "SELECT Friends_ID From Friends WHERE ID = '$ownID' "; 
    $oldFriendlist_result = mysqli_query($connection, $getFriendlist_q); 
    $oldFriendlist = mysqli_fetch_assoc($oldFriendlist_result)["Friends_ID"]; 
    //check if user isnt already friends with other user 
    $splitted = explode(";", $oldFriendlist); 


    if(in_array($friendID, $splitted)){ 
     echo "You are already Friends."; 
    } 
    else{ 
     //append ';' at the end of friendID 
     $friendID .= ';' ; 
     $updatedFriendlist = $oldFriendlist . $friendID; 
     $addID_query = "UPDATE Friends SET Friends_ID = $updatedFriendlist WHERE ID = $ownID "; 

     if ($connection->query($addID_query) === TRUE) { 
      echo "Friendlist updated successfully"; 
     } 
     else { 
      echo "Error updating Friendlist: " . $conn->error; 
     } 
    } 

    $connection->close(); 
} 

?> 

我有PHP或MySQL這使你的幫助,將不勝感激之前沒有任何經驗。

回答

0

第一你有一個大問題來連接一個SQL請求與 可變

$getOwnID_q = "SELECT ID FROM Users WHERE Username = '$username' "; 

成爲

$getOwnID_q = "SELECT ID FROM Users WHERE Username like ' ".$username." ' "; 

$getFriendID_q = "SELECT ID FROM Users WHERE Username = '$friend_username' "; 

成了

$getFriendID_q = "SELECT ID FROM Users WHERE Username like ' ".$friend_username." ' "; 

$getFriendlist_q= "SELECT Friends_ID From Friends WHERE ID = '$ownID' "; 

成了

$getFriendlist_q= "SELECT Friends_ID From Friends WHERE ID =".$ownID; 

$addID_query = "UPDATE Friends SET Friends_ID = $updatedFriendlist WHERE ID = $ownID "; 

成了

$addID_query = "UPDATE Friends SET Friends_ID = ".$updatedFriendlist." WHERE ID = ".$ownID;