我有一个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);
}
我应该如何返回SUM
的{{1}}({1}}?
希望你得到我想要的东西,提前非常感谢!
答案 0 :(得分: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'];
}
答案 1 :(得分: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_array
和mysqli_fetch_assoc
功能获取值。
在此示例中,我使用了mysql_fetch_array
,因为mysqli_fetch_array()
函数将结果行作为关联数组,数字数组或两者进行提取。 (从W3School取线)
而mysqli_fetch_assoc
只返回结果中的关联数组。
答案 2 :(得分: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。