Exercise : Grades

screenshot

Write a PHP page grades.php that takes a query parameter student and computes total homework points earned by that student. For example, grades.php?student=Marty will read marty.txt. The student input files consist of a single line of scores separated by spaces:

15 14 22 19 13

Print a heading, a bullet list of scores on each assignment, and the total at the bottom. If there is no text file for that student, print "no scores found."

Exercise Solution

<!DOCTYPE html>
<html>
	<head>
		<title>Grades</title>
	</head>
	<body>
		<?php
		$student = "";
		if (isset($_GET["student"])) {
			$student = $_GET["student"];
		}
		?>
		<h1>Grades for <?= $student ?></h1>
		<ul>
			<?php
			$filename = strtolower($student) . ".txt";
			...

Exercise Solution, continued

			if (file_exists($filename)) {
				$total = 0;
				$text = file_get_contents($filename);
				$scores = explode(" ", $text);
				foreach ($scores as $score) {
					$total += $score;
					?>
					<li><?= $score ?> points</li>
				<?php } ?>
				<li>TOTAL: <?= $total ?></li>
			<?php } else { ?>
				<li>no scores found. :-(</li>
			<?php } ?>
		</ul>
	</body>
</html>