我试图找到插入表中的一组成绩的gpa,成绩的列是varchar类型,我需要循环然后将它们转换为十进制,我很丢失,现在不怎么去对这个。任何帮助将不胜感激
继续我到目前为止,我一直在犯错:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Display GPA</title>
</head>
<body>
<?php
$host="XXXX";
$username="XXXX"; // Mysql username
$password="XXX"; // Mysql password
$db_name="XXXX"; // Database name
$tbl_name="gpa"; // Table name
// Connect to server and select databse.
$con=mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_select_db($con,"bparis") or die ("no database");
if(mysqli_connect_errno())
$con = false;
if(!$con) {
echo "Failed to connect to database server!";
}
else {
$result = mysqli_query($con,"SELECT grade FROM gpa");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
if($grade == 'A') {
$numberGrade = 4;
} elseif ($grade == 'A-') {
$numberGrade = 3.67;
} elseif ($grade == 'B+') {
$numberGrade = 3.33;
} elseif ($grade == 'B') {
$numberGrade = 3;
} elseif ($grade == 'B-') {
$numberGrade = 2.67;
} elseif ($grade == 'C+') {
$numberGrade = 2.33;
} elseif ($grade == 'C') {
$numberGrade = 2;
} elseif ($grade == 'C-') {
$numberGrade = 1.67;
} elseif ($grade == 'D') {
$numberGrade = 1;
} else {
$numberGrade = 0;
}
$totalGrade = ($totalGrade + $numberGrade)/$i;
array_pop($array);
}
$totalGrade;
echo " <h1>Your Grades and GPA Calculator</h1>
<hr />
<p />
<table border='1'>
<tr>
<th></th>
<th>Course Heading</th>
<th>Course Number</th>
<th>Credit Hours</th>
<th>Grade</th>
</tr>\r\n";
$result = mysqli_query($con, "SELECT * FROM gpa");
while($row = mysqli_fetch_array($result)) {
echo " <tr>\r\n";
echo " <td>" . $row['id'] . "</td>\r\n";
echo " <td>" . $row['heading'] . "</td>\r\n";
echo " <td>" . $row['courseNUM'] . "</td>\r\n";
echo " <td>" . $row['creditHours'] . "</td>\r\n";
echo " <td>" . $row['grade'] . "</td>\r\n";
echo " </tr>\r\n";
}
echo " </table>\r\n";
echo "<p />Your overall GPA:" .$totalGrade;
}
mysqli_close($con);
?>
</body>
答案 0 :(得分:5)
你真的不需要用PHP来做。 SQL非常有能力自行完成
SELECT AVG(
CASE gpa
WHEN 'A' THEN 4
WHEN 'A-' THEN 3.67
WHEN 'B+' THEN 3.33
-- .... and so on
ELSE 0
END
) AS avg_gpa
FROM table