2016-11-18 44 views
0

我創建了一個查詢來檢查「朋友關係」。基本上,friend_one/$user_id是用戶登錄和friend_two/$profile_user是其他用戶的ID ... ie:如果我點擊另一個用戶的配置文件在這裏,它是該用戶。在SELECT查詢上進行擴展

我的系統工作正常,除了當登錄用戶查看他們自己的配置文件。由於我的查詢正在檢查登錄的用戶查看其他配置文件,因此當登錄用戶查看他們自己的配置文件時,它會拋出未定義的變量錯誤。

有什麼我可以做我的SQLphp,我可以改變,所以當friend_one/user_id看法有自己的空間,它不拋出無法識別變量錯誤?

第一個無法識別的變量錯誤從這裏開始:if ($friend_status == 2) {。所以查詢不會引發錯誤。

錯誤顯示,因爲我永遠不會有一個用戶在這個表中與他們自己的關係。所以,我猜這個錯誤也會在查看「不滿意」的配置文件時發生。任何想法的方法來解決它?


編輯:

我原來的答覆有點難以理解。基本上唯一的一次朋友「關係」或插入到我的數據庫是如果一個用戶朋友的另一個用戶。所以,如果這個關係不在數據庫和我的查詢中,我想「放開它」,所以它不僅檢查friend_onefriend_two的關係。

$okay = true; 

//Checks 
if ($okay) { 
    $friend_sql = " 
     SELECT * 
     FROM friends 
     WHERE friend_one = ? 
     AND friend_two = ? 
    "; 
    $select_friend_stmt = $con->prepare($friend_sql); 
    $select_friend_stmt->execute(array($user_id, $profile_user)); 
    $friend_rows = $select_friend_stmt->fetchAll(PDO::FETCH_ASSOC); 
    foreach ($friend_rows as $friend_row) { 
     $select_friend_1 = $friend_row['friend_one']; 
     $select_friend_2 = $friend_row['friend_two']; 
     $friend_status = $friend_row['status']; 
     $friend_status_date = $friend_row['date']; 
    } 
} 
else { 
    echo "Friend Status not found."; 
} 
$friend_status_button = null; 
if ($friend_status == 2) { 
    $friend_status_button = "Approved"; 
} 
else if ($friend_status == 1) { 
     $friend_status_button = "Pending"; 
} 
else if ($select_friend_1 == $select_friend_2) { 
    $friend_status_button = null; 
} 
else { 
    $friend_status_button = "Add Friend"; 
} 
+0

爲什麼不檢查'$ user_id == $ profile_user',然後繞過這個檢查自己是否是'朋友'的整個代碼。 – Sean

+0

@Sean好主意,但是當我寫出這個問題時,我意識到任何非關係用戶仍然會爲我的查詢拋出一個錯誤。所以,我認爲這是更多情況來檢查'$ profile_user'是否不在數據庫中以允許查詢運行....但我仍然需要檢查'$ user_id == $ profile_user',就像你一樣指出。這是我的查詢和我剛剛指出的兩件事的結合......只是無法弄清楚如何編寫它。 – Paul

+0

在php中,你可以設置'$ friend_status'的默認值(即''friend_status = 0;'),只有在返回一行時纔會改變。這樣就不會在'if($ friend_status == ...'錯誤,或者如果你想總是從MySQL返回一行,你可以使用默認行值的'UNION' - 參見http:// stackoverflow .com/a/3417312/689579 – Sean

回答

0

如果這將是我,我會因爲你的參數是一個問號改變select語句

編輯我的發言(?)

SELECT * 
     FROM friends 
     WHERE friend_one = ? 
     AND friend_two = ? and (friend_one <> ? and friend_two <> ?) 

你下一個問題將是返回值,因爲這將返回null。所以,我會檢查$friend_rows數據,如果它等於零,那就趕上錯誤。

+0

這只是給了列沒有找到錯誤。我用我的初始查詢,只是添加'和(friend_one <> self和friend_two <> self)' – Paul

+0

讓我指出先生,「自我」應該是你的參數,在你的情況下,這將是? –

+0

請問,你的參數真的是一個問號嗎? –