-1
<?php 

    include '../config.php';

    function getAmount(){
        $sql = "SELECT sum(amount) AS total 
                FROM transaction 
                WHERE updated_at > '1501525800000' 
                    AND updated_at < '1504117800000'";

         $sumresult = mysqli_query($con,$sql);
         $sumrow=mysqli_fetch_assoc($sumresult);
         return $sumrow['total'];
    }

    $total = getAmount();
    echo $total;

?>

Hello There, I am new to PHP and I am getting the sum of all price in a particular month from my transaction table. But the value returned is empty, the query is working as well as the $total value is printed if I do not use function. But when I try to return value via function, nothing is printed. Help is really appreciated. Thanks in advance.

Meloman
  • 3,558
  • 3
  • 41
  • 51
topper1309
  • 151
  • 3
  • 16

2 Answers2

2

Define your $con as global inside the function:

include '../config.php';

function getAmount(){
    global $con;
    $sql = "SELECT sum(amount) AS total 
            FROM transaction 
            WHERE updated_at>'1501525800000' 
                AND updated_at<'1504117800000'";
    $sumresult = mysqli_query($con,$sql);
    $sumrow=mysqli_fetch_assoc($sumresult);
    return $sumrow['total'];
}

For more information about variable scope, you should read: http://php.net/manual/en/language.variables.scope.php

Meloman
  • 3,558
  • 3
  • 41
  • 51
okante
  • 151
  • 6
0

Try this :

<?php 

    include '../config.php';

    function getAmount($min, $max) {

        global $con;

        $sql = "SELECT sum(amount) AS total 
                FROM transaction 
                WHERE updated_at > '$min' 
                    AND updated_at < '$max'";

         $sumresult = mysqli_query($con, $sql);
         $sumrow    = mysqli_fetch_assoc($sumresult);

         return $sumrow['total'];
    }

    echo getAmount(1501525800000, 1504117800000);

?>

As you can see I also added $min and $max value as argument for the function getAmount.

Meloman
  • 3,558
  • 3
  • 41
  • 51