JohnSmith
JohnSmith

Reputation: 1557

How do I check if a value currently exist in a while loop?

Let's say I have this table in my database...

 id  | name  | beginventory | sold | datesold
    101 | rock  | 100          | 5    | 2011-9-12
    201 | paper | 50           | 10   | 2011-9-13
    301 | pen   | 30           | 20   | 2011-10-1
    101 | rock  | 100          | 10   | 2011-10-1
    101 | rock  | 100          | 10   | 2011-10-2
    201 | paper | 50           | 15   | 2011-10-3 

I want to display an output of...

  name  | current | sold | remaining | date sold
    rock  | 100     | 5    | 95        | 2011-9-12
    paper | 50      | 10   | 40        | 2011-9-13
    pen   | 30      | 20   | 10        | 2011-10-1
    rock  | 95      | 10   | 85        | 2011-10-1
    rock  | 85      | 10   | 75        | 2011-10-2
    paper | 40      | 15   | 25        | 2011-10-3

Here my script (doesn't work)

while($info = mysql_query($getinfo)){
$name = $info['name'].'<br />';
$beginventory = $info['beginventory'].'<br />';
$sold = $info['sold'].'<br />'
$remaining = $beginventory - $sold.'<br />';
$date = $info['datesold'].'<br />'
echo '<tr>';
echo '<td>'.$name.'</td>';
echo '<td>'.$current.'</td>';
echo '<td>'.$sold.'</td>';
echo '<td>'.$remaining.'</td>';
echo '<td>'.$date.'</td>';
echo '</tr>';
}

My question is how do I "tell" PHP in a while loop that if the "name" already exist, instead of using $beginventory to get $remaining it should use the previous $remaining to get the correct value for current.

I know it is easier if I stored the values in the database, this is my last option if I can't figure this out.

Upvotes: 0

Views: 218

Answers (1)

zerkms
zerkms

Reputation: 255015

$left = array();

while($info = mysql_query($getinfo)){

    if (!isset($left[$info['name']])) $left[$info['name']] = $info['beginventory'];
    $name = $info['name'].'<br />';
    $beginventory = $left[$info['name']].'<br />';
    $sold = $info['sold'].'<br />'
    $remaining = $beginventory - $sold.'<br />';
    $date = $info['datesold'].'<br />'
    echo '<tr>';
    echo '<td>'.$name.'</td>';
    echo '<td>'.$current.'</td>';
    echo '<td>'.$sold.'</td>';
    echo '<td>'.$remaining.'</td>';
    echo '<td>'.$date.'</td>';
    echo '</tr>';

    $left[$info['name']] -= $info['sold'];
}

Upvotes: 2

Related Questions