0

I have a list of requested items that are pulled from the database. What I am looking to do is to get the hourly_rate for each item that is selected and add those values together. I am getting the values I need from the database, but now I am looking to add those values.

//Get total hours from other query
$hours = $row['total_hours'];
//Items requested by user 
$requestedItems = "1,2,3";
$items = explode(',', $requestedItems);

//Query 
$priceQuery = "SELECT hour_rate,
                      day_rate,
                      item_id,
                      rental_status,
                      hourly_rental                                                     
                FROM
                      products
                WHERE
                      rental_status != 1
                AND
                      item_id = :var
                ";                              
$itemDisplay = array(); 

I loop through and get back the values, but now what I want is to add those returned values together...I tried turning them to integers and adding them together but could not seem to do it.

foreach($items as $var){
     $itemDisplay = $userFile->priceSelection($conn, $var, $priceQuery);
     foreach($itemDisplay as $key=>$v){
        //Edits added                           
        $itemVar += $v['hour_rate'];                                            
        if($hours >= 3){
            if($v['hourly_rental'] == '1'){
                $hours -= 2;
                $itemVar += $v['day_rate'] * $hours;
            }else{
                $itemVar += $v['day_rate']; 
            }                                               
        }else{
            if($v['hourly_rental'] == '1'){
                $itemVar += $v['day_rate'];
            }else{
                // This is the line here that is affecting the value of both items. 
                //If $day_rate = $v['day_rate']  then the items with hourly_rentals == '1'
                //have correct values. If I set $day_rate = 0; then the items with
                //hourly_rentals != '1' have correct values
                //but not both at the same time. Might need to figure out a better comparison. 

                $day_rate = $v['day_rate']; 

                 print_r($day_rate);
            }   
        }                                       
    }                                                                               
}

$totalPrice = $itemVar + $day_rate + $delivery_cost;

The price selection function just grabs the values from database (code for clarity)

public function priceSelection($conn, $var, $priceQuery){       
    $stmt = $conn->prepare($priceQuery);
    $stmt->bindParam(":var", $var);
    $stmt->execute();
    $result = $stmt->fetchAll();
    if($stmt->rowCount() > 0){
        foreach($result as $row){
            $array[] = $row; 
        }
        return $array;
    }
    return false;
}
Stuckfornow
  • 280
  • 1
  • 15

3 Answers3

4

Beside the option to Summarize the numbers within the SQL query you may do it in PHP as well.

Avoid resetting the value on each loop step and continuously add the value to $itemVar variable:

<?php
foreach($items as $var){
   $itemDisplay = $userFile->priceSelection($conn, $var, $priceQuery);
   foreach($itemDisplay as $key=>$v){
                                    
    //$itemVar = '';  // do not null the sum value
    //Items returned that I would like to be added together                                     
    $itemVar += $v['hour_rate'];
                                    
    //$values = intval($itemVar);
                                       
  }                                                                            
} 
print_r($itemVar); // print final value

EDIT after OP update

I see two issues in the updated OP code.

  1. the data in the variable $day_rate is set directly and only within the nested foreach loop so this variable keeps the very last value that is set each time the else - else condition is met AND it is the only place where the variable is initiated. This could make some troubles in final calculation.

  2. the $itemVar variable is incrementally calculating its total sum in each loop however the $day_rate is not and more over the problem mentioned in first point. You may need to make a sum of that value as well what you can achieve with this: $day_rate = $v['day_rate'];

  3. potential problem might be the comparison of (xxx == '1') as the PHP dynamically works with the variable entity it will take and convert the value of xxx to most probable to an integer and then converts the string of '1' to the integer as well befor the comparison is made. As an example gues how is compared var_dump(true == '1'); true or false, huh?

Note it is going to be XY problem since the whole structure starts not making any sense to me.


Last EDIT As general purpose tip for understanding what your code is doing I would recommend any kind of debugger where you can see live status of any variable while the script is processing. Debugging in PHP

Or very simple way of debugging that is simple printing the variable content so you can get at least some idea how to data are calculated.

And of course Always debug your scripts with enabled PHP Error Reporting!

// Counters for 
$itemsCounter = 0;
$displayCounter = 0;
foreach($items as $var){
     $itemDisplay = $userFile->priceSelection($conn, $var, $priceQuery);
     foreach($itemDisplay as $key=>$v){
        // Debug current variables rows and $v
        echo "Row $itemsCounter::$displayCounter; key=$key;". print_r($v, true);
        //Edits added                           
        $itemVar += $v['hour_rate'];                                            
        if($hours >= 3){ // WHERE do you get the $hours? Sould it be $v['hour_rate']?
            if($v['hourly_rental'] == '1'){
                $hours -= 2;
                $itemVar += $v['day_rate'] * $hours;
            }else{
                $itemVar += $v['day_rate']; 
            }
           // Debug current variable $itemVar
           echo "itemVar=$itemVar;"
        }else{
            if($v['hourly_rental'] == '1'){
                $itemVar += $v['day_rate'];
            }else{
                $day_rate = $v['day_rate']; 

                 print_r($day_rate);
            } 
            // Debug current variable $itemVar and new $day_rate
            echo "itemVar=$itemVar;day_rate=$day_rate;"  
        }
        $displayCounter++;  // iterrate the inner counter
    } 
    // iterrate the counter
    $itemsCounter++;
    // reset the inner counter for next loop
    $displayCounter = 0; 
    // Debug inserts new line
    echo PHP_EOL;
}

$totalPrice = $itemVar + $day_rate + $delivery_cost;
ino
  • 2,345
  • 1
  • 15
  • 27
  • 1
    This is technically incorrect, because the same result can be obtained with 1 request to the database – emrdev Feb 23 '22 at 09:52
  • @HarviDent OP asked how to get the sum of dynamic values from array. I assume the piece of code is the minimal working example without the rest of treating the data obtained from the database.. And yes, there are several way how to obtain the total sum but this is what OP asked for. – ino Feb 23 '22 at 09:58
  • @ino i tried both ways, your way seemed to get me closer to what I am looking to accomplish. I updated post with latest code. The issue now is that I am only getting the correct value on one or the other item. If I make the value of $day_rate like shown in the example, equal to $v['day_rate'], then all of my hourly_rentals have correct values, if I set it to zero then the daily_rate items have correct values & hourly_rentals are off by 1 day_rate. – Stuckfornow Feb 24 '22 at 05:05
  • @Stuckfornow I have added my update to the post. – ino Feb 24 '22 at 11:48
  • @ino yeah it is starting to get a little bit complicated, i'll take a look once again and try to rebuild it. – Stuckfornow Feb 24 '22 at 15:55
  • @Stuckfornow I have updated my answer with final edit about code debugging. More over I found one variable `$hours` that does not exists and you use it in the `if` statement. Hope this help you to improve your coding. If so please consider accepting the answer to mark it as solved. – ino Feb 25 '22 at 07:22
  • @ino yeah the $hours variable is grabbed from another query and fed to this one. It's a complicated system for displaying total amount of all items, since a single item can be a part of multiple orders and some can be ordered hourly while others daily. Appreciate the help. I'll grab a debugger and hopefully will get to a final solution! Debugger is a good idea. – Stuckfornow Feb 25 '22 at 07:28
  • @ino So I ended up changing a few things and finally got it figured out! I had to move my original query into the function that i created and then grabbed that function and sent it to another loop. Complicated and probably resource heavy but works for this small project. Updated question with answer. Appreciate the help ino – Stuckfornow Feb 25 '22 at 19:00
3

Maybe you just get the amount, it will solve your problem?

$sumHourlyRental = "SELECT SUM(hourly_rental) FROM products WHERE rental_status != 1 AND item_id = :var";   
emrdev
  • 2,155
  • 3
  • 9
  • 15
  • 1
    [Aggregate Functions](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html). This is much better suited to the database as is suggested here. Looping over rows in PHP is slow and how does that scale? – ficuscr Feb 23 '22 at 09:46
1

So to answer my own question, I needed to actually do the calculations within the function itself. It works as intended now

//Code on schedule.php page
//Find how many requested items there are
$items = explode(',', $requestedItems);
$item_name = array();
foreach ($items as $var){
    $item_name[] = $products->priceChange($conn, $var, $hours);
}
$prices = 0;
foreach($item_name as $price){
    $prices += $price;
}
$prices += $delivery_cost;                                  
echo '<button type="button" class="btn" style="color:green;font-weight:bold;">$'.$prices.'</button>';

Then in the function, I added up the values.

public function priceChange($conn, $var, $hours){   
    $query = "SELECT * FROM products WHERE item_id = :id";
    $stmt = $conn->prepare($query);
    $stmt->bindParam(":id", $var);
    $stmt->execute();
    $result = $stmt->fetchAll();
    if($stmt->rowCount() > 0){
        $total = 0;     
        foreach($result as $row){
            $hour_rate = $row['hour_rate'];
            $day_rate = $row['day_rate'];
            if($hours == '2'){                                                  
                $total += $hour_rate;                  
            }else{
                if($row['hourly_rental'] == '1'){
                    $hours -= 2;                    
                    $total += $hour_rate + $day_rate * $hours;
                }
                else{
                    $total = $hour_rate + $day_rate;
                }
            }
        }
        return $total;
    }
    return false;
}
Stuckfornow
  • 280
  • 1
  • 15