2017-08-22 58 views
0

我想計算兩個成員之間的會話數。 當用戶1訪問用戶2的配置文件時,我看到可見的結果。但是,當用戶2訪問配置文件1時,我沒有結果。rowCount where和OR與MySQL和PHP

public function getNumberConversations($sender, $receiver) { 

    $st = Database::getDatabase()->prepare("SELECT id, sender, receiver 
     FROM conversation 
     WHERE sender = ? AND receiver = ? 
     OR receiver = ? AND sender = ? 
    "); 

    $st->execute(array($sender, $receiver, $receiver, $sender)); 

    return $st->rowCount(); 

    } 
+1

'WHERE(發件人=和接收器=?) 或' – JYoThI

+0

另外,你要互換的發送者和接收者的兩倍(接收器=和發件人=?):在查詢和在數組中。淨結果:根本沒有交換,並且重複子句'WHERE(sender = $ sender AND receiver = $ receiver)OR(receiver = $ receiver AND sender = $ sender)' – bracco23

+0

我認爲在這種情況下括號不是問題 – etsa

回答

3

我想你應該改變

$st->execute(array($sender, $receiver, $receiver, $sender)); 

$st->execute(array($sender, $receiver, $sender, $receiver)); 

你的情況括號OK(和優先級)

2

使用括號爲條件

public function getNumberConversations($sender, $receiver) { 

    $st = Database::getDatabase()->prepare("SELECT id, sender, receiver 
     FROM conversation 
     WHERE (sender = ? AND receiver = ?) 
     OR (receiver = ? AND sender = ?) 
    "); 

    $st->execute(array($sender, $receiver, $sender, $receiver)); // also notice this 

    return $st->rowCount(); 

    } 
+0

I已經嘗試過但不起作用 – Manudog

+0

然後在你的問題中更新它,否則每個人都會有相同的答案 –

1

您需要爲分離條件設置廣告支架。你也交換條件,所以它會變得相同。試試以下的答案:

public function getNumberConversations($sender, $receiver) { 

    $st = Database::getDatabase()->prepare("SELECT id, sender, receiver 
     FROM conversation 
     WHERE (sender = ? AND receiver = ?) 
     OR (receiver = ? AND sender = ?) 
    "); 

    $st->execute(array($sender, $receiver, $sender, $receiver)); //<----change here also 

    return $st->rowCount(); 

    }