2015-06-27 164 views
2

考慮下面的代碼的mysql_query返回錯誤的結果

if (isset($_SESSION['FBID']) ) { 
    $uid  = $_SESSION['FBID']; 
    $sql  = "SELECT *, count(member_nr) AS notifyMe 
       FROM poolWinners 
       WHERE member_nr = '$uid' AND notification ='1'"; 
    $result = mysql_query($sql); 
    while($row=mysql_fetch_array($result)){ 
     $notification = $row['notifyMe']; 
    }//while 
     if ($notification > 0) { 
     echo '<span class="badge">' . $notification . '</span>'; 
    } //if 
    var_dump($notification); 
} //isset($_SESSION['FBID']) 

以上腳本返回成員有多少條信息有,你可以在圖像下方 enter image description here

我的問題

的看腳本返回錯誤的結果(錯誤的通知數量)。看看下面的表格,會員號碼在表格中出現3次如此: $notification = $row['notifyMe']應= 3而不是1

我在這裏丟失或做錯了什麼?感謝您閱讀

+0

總結的通知列中的值?因爲他們看起來每個都是1,就像這樣'select sumNot from poolWinners where member_nr ='$ uid'AND notification = 1;'不需要遍歷結果,直接得到總和 –

+0

或者執行select count(member_nr) from poolWinners where member_nr ='$ uid'and notification = 1;'並且使用計數而不是總和,以避免大於1的通知值。再次直接取滿值,不需要循環結果集 –

回答

1

使用

$sql  = "SELECT *, count(*) AS notifyMe 
      FROM poolWinners 
      WHERE member_nr = '$uid' AND notification ='1'"; 

通知count(*)時,將取回多條記錄是如何匹配標準。

並在開始時初始化$notification = 0;

+0

謝謝生病讓它去並讓你知道 –

+0

感謝隊友,但即時得到同樣的問題 –

+0

它仍然返回一(1)....怪異 –

1

,你是否嘗試從這個角度

$sql = "SELECT * FROM poolWinners WHERE member_nr = '$uid' AND notification ='1'"; 

$result = mysql_query($sql); 
$notification = array(); 
    while($row=mysql_fetch_array($result)){ 
     $notification[] = $row['notifyMe']; 
    } 
//an array count on notification should give you the number of elements in the array i.e those that matched the query 

$total_count = count($notification); 
+0

如果你正在處理少量的行,你可以嘗試mysql_num_rows查看返回的行數 – danidee

1

在代碼中接近它的通知將永遠之一,因爲它會在結果集中只有最後一排的notifyMe領域。

如果你想獲得通知的數量,試試這個

if (isset($_SESSION['FBID']) ) { 
    $uid  = $_SESSION['FBID']; 
    $sql  = "SELECT *, count(member_nr) AS notifyMe 
       FROM poolWinners 
       WHERE member_nr = '$uid' AND notification ='1'"; 
    $result = mysql_query($sql); 
    $notification = 0; 
    while($row=mysql_fetch_array($result)){ 
     $notification++; 
     /* 
     OR $notification += $row['notifyMe']; 
     */ 
    }//while 
     if ($notification > 0) { 
     echo '<span class="badge">' . $notification . '</span>'; 
    } //if 
    var_dump($notification); 
} //isset($_SESSION['FBID']) 
1
$sql  = "SELECT * 
      FROM poolWinners 
      WHERE member_nr = '$uid' AND notification ='1'"; 

$result = mysql_query($sql); 
$notification = mysql_num_rows($result); 
1
$sql = "SELECT * FROM poolWinners WHERE member_nr = '$uid' AND notification ='1'"; 

if ($result=mysqli_query($con,$sql)) 
    { 
    // Return the number of rows in result set 
echo "Toal notification".mysqli_num_rows($result); 
    } 

mysqli_close($con); 
?>