我有一个包含两个字段的表,分别命名为credithour
和gradepoint
。
我想将credithour
每一行的数据与gradepoint
相加。
$totalcredithour = 0;
$GPA = "SELECT * FROM $dept_stu_id WHERE sessionyear = '$sessionyear'" or die (mysql_error());
$resultGPA = mysql_query($GPA);
while($data = mysql_fetch_array($resultGPA))
{
$credithour = "$data[credithour]";
$gradepoint = "$data[gradepoint]";
echo $totalcredithour += $credithour;
}
我做错了什么?
它添加了数据,但除了结果还显示了第一个学分。假设,这里我输入了两个数据3和5。当我运行这段代码时,它回显38。这意味着"3+5=8"和第一个学分="3"。
实际上其他答案是错误的,你正在做or die(mysql_error());
旁边的字符串,这是不对的。
你的代码应该是这样的…
$totalcredithour = 0;
$GPA = "SELECT * FROM `".$dept_stu_id."` WHERE sessionyear = `".$sessionyear."` ";
$resultGPA = mysql_query($GPA) or die(mysql_error());
while($data = mysql_fetch_array($resultGPA, MYSQL_ASSOC))
{
$credithour = $data['credithour'];
$gradepoint = $data['gradepoint'];
echo $totalcredithour += $credithour; //Make sure `$totalcredithot` isn't null/doesn't exist.
}
在while循环中试试这样做:
$credithour = $data['credithour'];
$gradepoint = $data['gradepoint'];
像这样试试
我已经编辑了答案并添加了floatval函数
$totalcredithour = 0;
$GPA = "SELECT * FROM `".$dept_stu_id."` WHERE sessionyear = '".$sessionyear."'" or die (mysql_error());
$resultGPA = mysql_query($GPA);
while($data = mysql_fetch_array($resultGPA))
{
$credithour = $data['credithour'];
$gradepoint = $data['gradepoint'];
echo $totalcredithour += floatval($credithour);
}