为什么这个函数没有返回正确的结果?

时间:2017-09-06 13:01:16

标签: php sql mysqli

我通过创建两个函数“daySum()”和“yesterdaySum()”从数据库中获取数据。调用这些函数时,它分别返回正确的值54000和51000。

然后我将它们放入变量$ day和$昨天,但是当执行变量操作“$ day + $ yesterday”时它打印0.这将不允许我创建我的项目所需的条件。

你可以帮帮我吗?

提前致谢!

//DEFINING 2 FUNCTIONS: daySum() and yesterdaySum()

function daySum() {
    //connect to database
    require 'connect.php';

    // query
    $query = "SELECT sum(till_amount) FROM Cash ";
    $query .= "WHERE date ='2017-09-05'";
    $result = mysqli_query($connect, $query);

    // fetch
    while($row = mysqli_fetch_assoc($result)) {
        print_r($row["sum(till_amount)"]);
    }
}

function yesterdaySum() {
    //connect to database
    require 'connect.php';

    // query
    $query = "SELECT sum(till_amount) FROM Cash ";
    $query .= "WHERE date ='2017-09-04'";
    $result = mysqli_query($connect, $query);

    // fetch
    while($row = mysqli_fetch_assoc($result)) {
        print_r($row["sum(till_amount)"]);
    }
}

// PUTTING THEM INTO VARIABLE 

$day = daySum(); // sum is 54000
$yesterday = yesterdaySum(); // sum is 51000

    // adding $day plus $yesterday should print 105000
    // and here is the problem...

print($day + $yesterday); // it prints 0

//WHY????

1 个答案:

答案 0 :(得分:1)

您的功能 只是打印 。这就是为什么它的添加不起作用。

您必须更改下面的代码( 一些改进 ,这是评论的): -

<?php
require 'connect.php'; //don't add multiple time
function daySum() {
    $query = "SELECT sum(till_amount) FROM Cash WHERE date ='2017-09-05'";
    $result = mysqli_query($connect, $query);
    while($row = mysqli_fetch_assoc($result)) {
        return $row["sum(till_amount)"]); //return value
    }
}

function yesterdaySum() {
    $query = "SELECT sum(till_amount) FROM Cash WHERE date ='2017-09-04'";
    $result = mysqli_query($connect, $query);
    while($row = mysqli_fetch_assoc($result)) {
       return $row["sum(till_amount)"]); //return value
    }
}

$day = daySum(); // now $day have value
$yesterday = yesterdaySum(); //now $yesterday have value


print((int)$day + (int)$yesterday); // it will work fine now

现在最简单的是 use BETWEEN query: -

<?php
require 'connect.php'; //don't add multiple time
function daySum() {
    $query = "SELECT sum(till_amount) FROM Cash WHERE date BETWEEN '2017-09-04' AND '2017-09-05'";
    $result = mysqli_query($connect, $query);
    while($row = mysqli_fetch_assoc($result)) {
        return $row["sum(till_amount)"]);
    }
}

$day = daySum();

print($day);

注意: - 可能是您的家庭作业任务,但开始了解 prepared statements 今天为了防止您的查询来自 SQL INJECTION 。这是非常重要和必要的。