Logo  

CS479/579 - Web Programming II

Displaying exercises/e10/solution/gradebook.php

<?php
$myconn = new mysqli("localhost", "sbaker", "sbaker", "sbaker");
$students = [];
$tests = [];

$res = $myconn->query("select sid, name from students");
while ($row = $res->fetch_assoc()) {
  $students[$row['sid']] = $row['name'];
}
$res->close();

$res = $myconn->query("select tid, name, points from tests") or die($myconn->error);
while ($row = $res->fetch_assoc()) {
  $tests[$row['tid']] = [ "name" => $row['name'], "points" => $row['points'] ];
}
$res->close();

?>
<!DOCTYPE html>
<html>
<head>
 <title> Gradebook </title>
 <meta charset='utf-8'>
 <style>
 input { width: 50px;  text-align: right;}
 </style>
 <script>
 function loadurl(url, data, callback) {
   var req = new XMLHttpRequest();
   req.open("POST", "update.php", true);
   req.onreadystatechange = function() {
     if (req.readyState == 4 && req.status == 200)
       callback(JSON.parse(req.responseText));
   }
   req.send(data);
 }
 function update(e, tid, sid) {
   var f = new FormData();
   f.append("tid", tid);
   f.append("sid", sid);
   f.append("points", e.value);
   console.log(tid, sid, e.value);
   e.value = "";
   loadurl("update.php", f, function(data) {
     console.log("received ", data);
     e.value = data;
     sid++;
     var n = document.getElementById("i"+tid+"."+sid);
     if (n == undefined) {
       sid = 1;
       tid++;
       n = document.getElementById("i"+tid+"."+sid);
     }
     if (n != undefined) n.focus();
   });
 }
 function move(ev, e, tid, sid) {
   switch(ev.code) {
     case "ArrowUp":
       sid--;
       if (sid < 1) sid = 10;
       break;
     case "ArrowDown":
       sid++;
       if (sid > 10) sid = 1;
       break;
     case "ArrowLeft":
       if (e.selectionStart != 0) return;
       tid--;
       if (tid < 1) tid = 3;
       break;
     case "ArrowRight":
       if (e.selectionStart != e.value.length) return;
       tid++;
       if (tid > 3) tid = 1;
       break;
   }
   var n = document.getElementById("i"+tid+"."+sid);
   if (n != undefined) n.focus();
 }
 </script>
</head>
<body>
<table>
 <thead>
 <tr> <th> Name: <?php
 foreach($tests as $test) {
   echo "<th>" . $test['name'] . "<br>" . $test['points'];
 }
 echo "<th> Total: \n";
 ?>
 </thead>
 <tbody>
 <?php
  $stmt = $myconn->prepare("select points from grades where sid=? and tid=?");
  $stmt->bind_param("ii", $sid, $tid);
  $stmt->bind_result($points);

  for($sid=1; $sid <= 10; $sid++) {
    echo "<tr> <th>" . $students[$sid];
    for($tid=1; $tid <= 3; $tid++) {
      $stmt->execute();
      $stmt->fetch();
      if ($points === null) $points = '';
      echo "<td> <input id='i$tid.$sid'
        onchange='update(this,$tid,$sid);'
        onkeydown='move(event,this,$tid,$sid);'
        type='text' value='$points'>";
    }
    echo "\n";
  }
 ?>
 </tbody>
</table>
</body>
</html>