2015-06-27 166 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); 
?>