2016-01-26 102 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。