5

Why this variable increment of the loop?

 2 years ago
source link: https://www.codesd.com/item/why-this-variable-increment-of-the-loop.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Why this variable increment of the loop?

advertisements

I'm trying to write code that will count the number of users returned by a sqlite query and then split a 'bill' between those users, but for some reason my counter won't increment and I am getting a division by zero error. My code is here:

<?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.'');
?>

Anyone have any ideas on how to fix this?


Regardless of the loop not seeming to work, you can't have two while(... fetchArray()) loops without something resetting the internal pointer.

In this case, however, you don't need that:

$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()) {
    ...
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK