2

I got stuck, my objective was to get the ProductID, hidden inside the $_SESSION['cart'] and then use those ID in an sql query to compute the sum

here's my code

public function getProductID(){
    $keys = array_keys($_SESSION['cart']);
    return $keys;
}


public function getShippingFee(){
    $ids = $this->getProductID();
    foreach($ids as $id){
    $query = mysql_query("SELECT * FROM deliverycharges WHERE ProductID = $id");
    $row = mysql_fetch_assoct($query);
    $sum = $row['Cost'] + $row['Tax'];
    return $sum;   
  }
}

the second function that I pasted is wrong, I have done several type of looping and yet, I can't get the real sum..shame on me

4
  • What sort of error are you getting? Commented Jan 23, 2012 at 14:43
  • Before you can create a sum, you need to know of what to create the sum. That's entirely not clear from your question. In general you create a sum by using +, so your code looks good. Commented Jan 23, 2012 at 14:43
  • It isn't advisable to perform a query inside a loop. You'd better build a single query to retrieve all the results and then parse them with a loop. Apart from that, you'd better escape that $id var before passing it to MySQL, just to be sure. Commented Jan 23, 2012 at 14:44
  • You are overwriting the $sum variable in the for-each loop. Try this instead: $sum += $row['Cost'] + $row['Tax']; Commented Jan 23, 2012 at 14:47

2 Answers 2

6

After you return, the function is exited, so you need to sum everything up at first and then return that after everything is summed up:

public function getShippingFee(){
    $ids = $this->getProductID();
    foreach($ids as $id){
      $query = mysql_query("SELECT * FROM deliverycharges WHERE ProductID = $id");
      $row = mysql_fetch_assoc($query);
      $sum += $row['Cost'] + $row['Tax'];
    }
    return $sum; 
}
Sign up to request clarification or add additional context in comments.

Comments

0

You are overwriting the value of sum each loop. Use +=

public function getShippingFee() {
    $ids = $this->getProductID();
    $sum = 0;
    foreach($ids as $id) {
        $query = mysql_query("SELECT * FROM deliverycharges WHERE ProductID = $id");
        $row = mysql_fetch_assoct($query);
        $sum += $row['Cost'] + $row['Tax'];
    }
    return $sum;   
}

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.