# Functions.php

**URL:** <https://www.phphelp.com/t/functions-php/36079>\
**Category:** General PHP Help\
**Created:** [March 18, 2024, 11:57am UTC](https://www.phphelp.com/t/functions-php/36079 "2024-03-18T11:57:39Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![dmanghani](https://www.phphelp.com/letter_avatar_proxy/v4/letter/d/e9c0ed/32.png) [@dmanghani](https://www.phphelp.com/u/dmanghani)\
**Post date:** [March 18, 2024, 11:57am UTC](https://www.phphelp.com/t/functions-php/36079/1 "2024-03-18T11:57:39Z")

</div>

I was using the following code repeatedly

```auto

$query="SELECT * FROM holdings WHERE type='14'";
$result = mysqli_query($conn, $query) or die('Unable to shares'.mysqli_error($conn));
while ($row = mysqli_fetch_assoc($result)) {
    $code=$row['name'];
    $id=$row['id_holding'];
    

    $query_buy="SELECT * FROM buy WHERE id_holding=$id";
      $result_buy = mysqli_query($conn, $query_buy) or die('Unable to shares'.mysqli_error($conn));
      while ($row_buy = mysqli_fetch_assoc($result_buy)) {
      $buy_qty=$row_buy['buy_qty'];
      $buy_rate=$row_buy['buy_rate'];
      $buy_total=$buy_rate*$buy_qty;
      $n++;
      echo "<table><td>$n.$code.</td>";
        echo "<td>".number_format($buy_qty,0)."</td>";
        echo "<td style='text-align: right;'>".number_format($buy_rate,2)."</td>";
        echo "<td style='text-align: right;'>".number_format(($buy_total),2)."</td>";
        $buy_total_share+=$buy_total;
        echo "<td>".$buy_total_share."</table>";        
}

}
```

so I made it a function as follows

```auto
   
        function buyrate($id) {
          $conn = mysqli_connect('localhost', 'root', '12May@61', 'investments');
          
            $query_buy="SELECT * FROM buy WHERE id_holding=$id";
              $result_buy = mysqli_query($conn, $query_buy) or die('Unable to shares'.mysqli_error($conn));
              while ($row_buy = mysqli_fetch_assoc($result_buy)) {
              $buy_qty=$row_buy['buy_qty'];
              $buy_rate=$row_buy['buy_rate'];
              $buy_total=$buy_rate*$buy_qty;
                echo "<td><center>".number_format($buy_qty,0)."</td>";
                echo "<td style='text-align: right;'>".number_format($buy_rate,2)."</td>";
                echo "<td style='text-align: right;'>".number_format(($buy_total),2)."</td>";
                $buy_total_share+=$buy_total;
                $_SESSION['buy_total_share']=$buy_total_share;
        }
```

the only thing that is not working is “$buy\_total\_share+=$buy\_total;”  
in the first instance, it does the totaling correctly bu as a function It simply returns the last value!  
also I have to add the $conn statement in every function and the include config.php does not work!  
Help Please

---

<div class="post-metadata">

**Author:** ![phdr](https://www.phphelp.com/letter_avatar_proxy/v4/letter/p/91b2a8/32.png) [@phdr](https://www.phphelp.com/u/phdr)\
**Post date:** [March 18, 2024, 1:51pm UTC](https://www.phphelp.com/t/functions-php/36079/2 "2024-03-18T13:51:26Z")

</div>

here are some general points about the code -

1. don’t run queries inside of loops or call a function that preforms a query inside of a loop. this is extremely inefficient. use a single (LEFT) JOIN query to get all the data that you want at one time
2. don’t use or die(…) for error handling. you should use exceptions for database error handling (this is the default setting now in php8+)
3. don’t use SELECT \*. list out the columns you are selecting in a query
4. don’t copy variables to other variables for nothing. just use the original variables that data is in
5. you can calculate the buy\_total in the sql query
6. your html markup is broken/incomplete. you need to validate the resulting web pages at [validator.w3.org](http://validator.w3.org)

some function specific points -

1. your application should make one database connection, then supply it to any function that needs it as a call-time parameter
2. you should separate the database specific code, that knows how to query for and fetch data, from the presentation code, that knows how to produce the output from the data. when using functions, these should be performed by separate functions
3. functions should return the result they produce to the calling code
4. the reason the buy\_total\_share isn’t working is because you are starting over with a new local $buy\_total\_share variable in each function call. if you separate the code as suggested, you can calculate the sum by operating on the fetched data all at one time, using php’s built-in array functions.

---

<div class="post-metadata">

**Author:** ![dmanghani](https://www.phphelp.com/letter_avatar_proxy/v4/letter/d/e9c0ed/32.png) [@dmanghani](https://www.phphelp.com/u/dmanghani)\
**Post date:** [March 19, 2024, 8:50am UTC](https://www.phphelp.com/t/functions-php/36079/3 "2024-03-19T08:50:09Z")

</div>

Just learnt about LEFT JOIN thanks,  
understood rest. Thanks again for pointing out these errors, will keep them in mind.  
However your reply about the function has left me totally confused, would you kindly give an example so I can understand? How do I use the array function to do the addition?  
Thanks again

---

<div class="post-metadata">

**Author:** ![phdr](https://www.phphelp.com/letter_avatar_proxy/v4/letter/p/91b2a8/32.png) [@phdr](https://www.phphelp.com/u/phdr)\
**Post date:** [March 19, 2024, 12:48pm UTC](https://www.phphelp.com/t/functions-php/36079/4 "2024-03-19T12:48:28Z")

</div>

If you calculate the buy\_total in the query and fetch all the rows of data into a php variable, e.g. $data, you can calculate the buy\_total\_share using -

```auto
$buy_total_share = array_sum(array_column($data,'buy_total'));
```

---

<div class="post-metadata">

**Author:** ![dmanghani](https://www.phphelp.com/letter_avatar_proxy/v4/letter/d/e9c0ed/32.png) [@dmanghani](https://www.phphelp.com/u/dmanghani)\
**Post date:** [March 20, 2024, 9:23am UTC](https://www.phphelp.com/t/functions-php/36079/5 "2024-03-20T09:23:33Z")

</div>

$buy\_total\_share = array\_sum(array\_column($data,‘buy\_total’)); should the  
‘buy\_total’ be ‘$buy\_total’?  
I think I am missing some step

Please see the revised code, this gives the total correctly as it should for each “$buy\_total=$buy\_rate\*$buy\_qty;” to the array

How do I sum this?

```auto
function buyrate($id) {
          $total=[];
          $conn = mysqli_connect('localhost', 'root', '12May@61', 'investments');
           $query_buy="SELECT * FROM buy WHERE id_holding=$id";
              $result_buy = mysqli_query($conn, $query_buy) ;
              while ($row_buy = mysqli_fetch_array($result_buy)) {
              $buy_qty=$row_buy['buy_qty'];
              $buy_rate=$row_buy['buy_rate'];
              $buy_total=$buy_rate*$buy_qty;
                 }
          array_push($total,$buy_total);
         $total=array_sum($total);
          echo $total.<"br">;
```

---

<div class="post-metadata">

**Author:** ![phdr](https://www.phphelp.com/letter_avatar_proxy/v4/letter/p/91b2a8/32.png) [@phdr](https://www.phphelp.com/u/phdr)\
**Post date:** [March 20, 2024, 9:59am UTC](https://www.phphelp.com/t/functions-php/36079/6 "2024-03-20T09:59:07Z")

</div>

As previously posted -

> [@phdr](#):
>
> you can calculate the buy\_total in the sql query

> [@phdr](#):
>
> If you calculate the buy\_total in the query …

Note: mysqli has a fetch\_all() statement. No looping is required to fetch the data.
