Php计数不能用于我的通知

时间:2015-01-19 10:06:44

标签: php mysqli

当我回显''.$count.''时,显示11101101。但我希望总计数为8或7等。请在我的代码中找到错误。

我曾经尝试$count = mysqli_num_rows($u);,但结果相同。

我的代码:

    $g = mysqli_query($dbh,"SELECT id FROM update WHERE from_id`='".$b."' OR `to_id`='".$session->id."'") or die(mysqli_error($dbh));
    while ($rows = mysqli_fetch_assoc($g)) {
    $ids[]= $rows['id'];
}   
foreach ( $ids as $id ){
    $u = mysqli_query($dbh,"SELECT id FROM updateside WHERE `id`='".$id."' AND `view` = '0'") or die(mysqli_error($dbh));
    $count = mysqli_affected_rows($dbh);
    while ($rows = mysqli_fetch_assoc($u)) {
    $nid= $rows['id'];
} 

echo ''.$count.'';

} 

4 个答案:

答案 0 :(得分:2)

将总计数分配给这样的变量:

假设mysqli_num_rows需要查询结果$u作为参数。

$total = 0;    

foreach ( $ids as $id ){
    $u = mysqli_query($dbh,"SELECT id FROM updateside WHERE `id`='".$id."' AND `view` = '0'") or die(mysqli_error($dbh));
    $count = mysqli_num_rows($u);
    $count = ($count == "") ? 0 : $count;
    $total = $total + $count;
    while ($rows = mysqli_fetch_assoc($u)) {
        $nid= $rows['id'];
    }
} 

echo $total;

答案 1 :(得分:2)

您需要稍微更改代码

foreach ( $ids as $id ){
    $u = mysqli_query($dbh,"SELECT id FROM updateside WHERE `id`='".$id."' AND `view` = '0'") or die(mysqli_error($dbh));
    while ($rows = mysqli_fetch_assoc($u)) {
        $nid= $rows['id'];
    }
    echo mysqli_num_rows($u);
}

如果您需要在所有foreach语句之后回显使用此

$count=0;
foreach ( $ids as $id ){
    $u = mysqli_query($dbh,"SELECT id FROM updateside WHERE `id`='".$id."' AND `view` = '0'") or die(mysqli_error($dbh));
    while ($rows = mysqli_fetch_assoc($u)) {
        $nid= $rows['id'];
    }
    $count = $count + mysqli_num_rows($u);
}
echo $count;

答案 2 :(得分:0)

你可以简单地使用

$count=$u->num_rows;

echo $count;

答案 3 :(得分:0)

我认为您的问题只是格式化错误。为什么在这里使用''? 试着写一下:

echo $count;