2016-01-26 76 views
0

我有一个SQL表,用于存储用户每天摄入的水量。我想选择当前日期的用户摄入量。我觉得我做的是正确的,只是不知道如何返回数字:从函数返回总和

function intake_so_far(){ 
    $connection=get_db(); 
    $email=$_SESSION['email']; 
    $datetoday=date("Y-m-d"); 
    $sql="SELECT SUM(intake_amount) FROM intake WHERE intake_email='$email' AND date(intake_date)='$datetoday'"; 
    $q=mysqli_query($connection,$sql); 
} 

我应该如何返回(intake_amount)的SUM AS $intake_so_far

希望你得到我想要的,非常感谢提前!

+0

你现在得到什么? – Shaharyar

+0

http://www.w3schools.com/php/func_mysqli_fetch_array.asp使用mysqli_fetch_array得到您的结果。并返回你的结果。 – ameenulla0007

回答

1

你可以得到(intake_amount)的总和$intake_so_fa为:

function intake_so_far() 
{ 
    $connection = get_db(); 
    $email=$_SESSION['email']; 
    $datetoday=date("Y-m-d"); 
    $sql = "SELECT SUM(intake_amount) AS intake_so_far FROM intake WHERE intake_email = '$email' 
    AND DATE(intake_date) ='$datetoday'"; 
    $res = mysqli_query($connection,$sql); 
    $row = mysqli_fetch_array($res); 
    $intake_so_far = $row['intake_so_far']; 
    return $intake_so_far; // return sum of this value 
} 

您可以使用mysqli_fetch_arraymysqli_fetch_assoc函数获取值。

在这个例子中,我使用了mysql_fetch_array,因为mysqli_fetch_array()函数会将结果行作为关联数组或数组数组或两者来获取。 (从W3School获取线路)

mysqli_fetch_assoc将返回结果中只有关联数组。

1
function intake_so_far(){ 
    $connection=get_db(); 
    $email=$_SESSION['email']; 
    $datetoday=date("Y-m-d"); 
    $sql="SELECT SUM(intake_amount) AS intake_so_far FROM intake WHERE intake_email='$email' AND date(intake_date)='$datetoday'"; 
    $res=mysqli_query($connection,$sql); 
    $row = mysqli_fetch_assoc($res); 
    return $row['intake_so_far']; 
} 
0
function intake_so_far(){ 
$connection=get_db(); 
$email=$_SESSION['email']; 
$datetoday=date("Y-m-d"); 
$sql="SELECT SUM(intake_amount) FROM intake WHERE intake_email='$email' AND date(intake_date)='$datetoday'"; 
$q=mysqli_query($connection,$sql); 
$getSum = mysqli_fetch_array($q, MYSQLI_ASSOC); 
return $getSum[0]; 
} 

http://php.net/manual/en/mysqli-result.fetch-array.php 退房教程参考mysqli_fetch_array。