mysql_query返回错误的结果

时间:2015-06-27 04:51:47

标签: php mysql

考虑以下代码

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

我在这里错过了什么或做错了什么?感谢您的阅读

5 个答案:

答案 0 :(得分:1)

使用

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

注意count(*),它将获取匹配条件的记录数。

并在开始时初始化$notification = 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);

答案 2 :(得分:1)

在您的代码中,通知将始终为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'] )

答案 3 :(得分:1)

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

$result = mysql_query($sql);
$notification = mysql_num_rows($result);

答案 4 :(得分: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);
?>