使用MYSQL

时间:2017-08-31 07:27:39

标签: php mysql function return return-value

<?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;

?>

您好,我是PHP的新手,我从交易表中得到特定月份内所有价格的总和。但是返回的值是空的,如果我不使用函数,查询工作以及打印 $ total 值。但是当我尝试通过函数返回值时,不会打印任何内容。非常感谢帮助。提前致谢。

2 个答案:

答案 0 :(得分:2)

在函数中定义$ con为全局:

{
    "config": {
        "platform": {
            "php": "7.0"
        },
    },
    "require": {
        "php": ">=5.5.9",
        "doctrine/doctrine-bundle": "^1.6",
        "doctrine/doctrine-cache-bundle": "^1.2",
        "doctrine/orm": "^2.5",
        "incenteev/composer-parameter-handler": "^2.0",
        "misd/phone-number-bundle": "^1.2",
        "sensio/distribution-bundle": "^5.0",
        "sensio/framework-extra-bundle": "^3.0.2",
        "symfony/monolog-bundle": "^3.0.2",
        "symfony/polyfill-apcu": "^1.0",
        "symfony/swiftmailer-bundle": "^2.3.10",
        "symfony/symfony": "3.3.*",
        "twig/twig": "^1.0||^2.0"
    }
}

有关变量范围的更多信息,请阅读:http://php.net/manual/en/language.variables.scope.php

答案 1 :(得分:0)

试试这个:

<?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);

?>

正如您所看到的,我还添加了$ min和$ max值作为函数getAmount的参数。