0

我正在尝试编写代码来计算 sqlite 查询返回的用户数量,然后在这些用户之间拆分“账单”,但由于某种原因,我的计数器不会增加,并且我得到除以零错误。我的代码在这里:

<?php
session_start();
require 'database.php';
$db = new Database();
$name = $_POST['name'];
$amount = $_POST['amount'];
$due = $_POST['due'];
$gid = $_GET['gid'];
$uid = $_SESSION['id'];
$count = 0;

$users = $db->query("select * from members where(gid='$gid');");
while($data = $users->fetchArray()) {
$count++;
}

$amount = $amount / $count;
while($data = $users->fetchArray()) {
if($data['uid'] == $uid) {
    continue;
} else {
    $temp = $data['uid'];
    $db->exec("insert into bills values(NULL,'$gid','$uid','$temp','$amount','$due','false','$name');");
}
}

header('Location:grouppage.php?gid='.$gid.'');
?>

有人对如何解决这个问题有任何想法吗?

4

2 回答 2

0

不管循环似乎不起作用,如果while(... fetchArray())没有重置内部指针,就不能有两个循环。

但是,在这种情况下,您不需要:

$users = $db->query("select * from members where(gid='$gid')");
$count = $users->numRows();
if( $count == 0) die("No users found!");
$amount /= $count;
while($data = $users->fetchArray()) {
    ...
}
于 2013-03-11T23:04:13.987 回答
0

当 select 不返回任何记录时,您不处理大小写。

看看你的代码:

$users = $db->query("select * from members where(gid='$gid');");
while($data = $users->fetchArray()) {
$count++;
}

未选择数据 - 未执行 while-body,$count 未递增并保留为零,因此在下一行中出现“除以零”错误。

$amount = $amount / $count;
于 2013-03-11T23:14:32.400 回答