0

Okay. so the site im making as a school project is almost done. But im having some problems with this last bit.

On the site a person is able to select some merchandise in a multi-select form on the first page.

The ID's of those merchandise is then sendt to the page im working on.. Here the price of the merchandise is selected from the database where the id's mach. (the price is the row "kunde_pris")

Now they are supposed to add or subtract there values. But I can't seem to get it to work the right way..

The code I got so far is this

$test = $_POST['tilbehor'];
$test=implode(',',$test);
$query = "SELECT * FROM tilbehor WHERE t_id IN ($test)";
$result = $db->query($query);
$num_rows = $result->num_rows;
    if($num_rows > 0) {
        while($row = mysqli_fetch_array($result)) {

            $number = 10 + 20 + $row['kunde_pris'];
            echo "$number ";

        }
        } else {
        echo "error";
        } 

The result I get from this is "1710 2430". So it takes the values it gets from $_POST['tilbehor'] wich right now is id 2 and 19. It then goes in the database and finds the merchandise wher the ID = the id's from the POST. the price in the database of those two merchandise are 1680 and 2400. so when i try to use the math i get 10+20+1680=1720 AND 10+20+2400=2430 when what I want is 10+20+1680+2400=4110

Any idea on how to solve this?

2
  • Initialize $number before the loop with 10+20 and inside the loop update its value by adding the price of the current row. Commented Feb 4, 2015 at 16:41
  • @Barmar gave a good answer. But by the way, you should better learn math i try to use the math i get 10+20+1680=1720 that is really not using math :-) or maybe that is just typo, sorry then :-) Commented Feb 4, 2015 at 17:47

1 Answer 1

2

You need to add to the previous value of $number, not replace the value each time through the loop.

$number = 10 + 20;
while ($row = mysqli_fetch_array($result)) {
    $number += $row['kunde_pris'];
}
echo $number;

Of course, you could also just calculate the total in your query:

SELECT 10+20+SUM(kunde_pris) AS total 
FROM tilbehor
WHERE t_id IN ($test);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.