Can't Create Assignments

Hello, Viv here! :wave:
I’m having an issue with some PHP code I made. Basically, you can add your classes and once there’s at least one class you can add your assignments. It should prioritize all your assignments based on…

  • Percent in class (lower = higher priority)
  • Due date minus current date (lower = higher priority)
  • Point value (higher = higher priority)

The issue on the table…I can’t seem to create any assignments–it just resets the form! I don’t get what I did wrong, can anyone help?

<?php
$cookies = $_COOKIE;

$classes = array();
foreach ($cookies as $key => $value) {
  if (substr($key, 0, 2) === "c-") {
    $classes[$key] = $value;
  }
}

echo '<h3>Add a Class:</h3>';
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">
Class Name: <input type="text" name="className"><br>
Percentage: <input type="number" name="classPercentage" min="0" max="100"><br>
<input type="submit" value="Add Class">
</form><br>';

if (isset($_POST['className']) && isset($_POST['classPercentage'])) {
  setcookie("c-" . urlencode(strtoupper($_POST['className'])), $_POST['classPercentage'], time() + 60 * 60 * 24 * 30);
  header("Location: " . $_SERVER['PHP_SELF']);
}

if (!empty($classes)) {
  $assignments = array();
  foreach ($cookies as $key => $value) {
    if (substr($key, 0, 2) === "a-") {
      $assignments[$key] = json_decode($value, true);
    }
  }
  
  usort($assignments, function($a, $b) use ($classes) {
    $diff = strtotime($a["dueDate"]) - strtotime($b["dueDate"]);
    if ($diff !== 0) {
      return $diff;
    }
    
    $diff = $b["points"] - $a["points"];
    if ($diff !== 0) {
      return $diff;
    }
        return $classes[$a["className"]] - $classes[$b["className"]];
  });
  
  echo '<h3>Add an Assignment:</h3>';
  echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">
  Assignment Name: <input type="text" name="assignmentName"><br>
  Points: <input type="number" name="assignmentPoints"><br>
  Due Date: <input type="date" name="assignmentDueDate"><br>
  Class: <select name="assignmentClass">';
  foreach ($classes as $key => $value) {
    echo '<option value="' . $key . '">' . substr($key, 2) . ' (' . $value . '%)</option>';
  }
  echo '</select><br>
  <input type="submit" value="Add Assignment">
  </form><br>';
  
if (isset($_POST['assignment-name']) && isset($_POST['assignment-points']) && isset($_POST['assignment-due-date']) && isset($_POST['class-select'])) {
    $assignmentName = $_POST['assignment-name'];
    $assignmentPoints = $_POST['assignment-points'];
    $assignmentDueDate = $_POST['assignment-due-date'];
    $assignmentClass = $_POST['class-select'];
    setcookie("a-$assignmentName", "$assignmentPoints,$assignmentDueDate,$assignmentClass", time() + (86400 * 30), "/"); 
}

$assignments = array();
foreach ($_COOKIE as $key => $value) {
    if (substr($key, 0, 2) == "a-") {
        $assignments[$key] = explode(",", $value);
    }
}

usort($assignments, function($a, $b) use ($classes) {
    $aDueDate = strtotime($a[1]);
    $bDueDate = strtotime($b[1]);
    $aPoints = $a[0];
    $bPoints = $b[0];
    $aClassPercent = $classes[$a[2]];
    $bClassPercent = $classes[$b[2]];
    
    if ($aDueDate - time() == $bDueDate - time()) {
        if ($aClassPercent == $bClassPercent) {
            return $aPoints > $bPoints ? -1 : 1;
        }
        return $aClassPercent < $bClassPercent ? -1 : 1;
    }
    return ($aDueDate - time()) < ($bDueDate - time()) ? -1 : 1;
});

echo "<table>";
echo "<tr><th>Assignment</th><th>Due Date</th><th>Points</th><th>Class</th><th>Action</th></tr>";
foreach ($assignments as $key => $assignment) {
    $assignmentName = substr($key, 2);
    $assignmentDueDate = $assignment[1];
    $assignmentPoints = $assignment[0];
    $assignmentClass = $assignment[2];
    echo "<tr>";
    echo "<td>$assignmentName</td>";
    echo "<td>$assignmentDueDate</td>";
    echo "<td>$assignmentPoints</td>";
    echo "<td>$assignmentClass</td>";
    echo "<td><button onclick='deleteAssignment(\"$key\")'>I'm Done!</button></td>";
    echo "</tr>";
}
echo "</table>";
}
?>

All help is appreciated!

Sounds like a homework assignment? :thinking:

My first suggestion would to separate PHP and HTML as that is just adding to your confusion (as well as mine :rofl:).

PHP should go on top and HTML on the bottom though there are times you have to sprinkle PHP into the HTML.

Here’s an example: (Sorry it’s a little long)

<?php
require_once 'assets/config/config.php';
require_once "vendor/autoload.php";

use FanOfLEGO\CMS;
use FanOfLEGO\Pagination_New as Pagination;
use FanOfLEGO\Login;
$_SESSION['loggedIn'] = false;
$login = new Login();

if ($login::memberCheck()) {
    header("Location: members.php");
    exit();
}


if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $login = new Login($_POST['user']);
    $login->login();
}


/*
 * Using pagination in order to have a nice looking
 * website page.
 */

if (isset($_GET['page']) && !empty($_GET['page'])) {
    $current_page = urldecode($_GET['page']);
} else {
    $current_page = 1;
}

$per_page = 12; // Total number of records to be displayed:
$total_count = CMS::countAllPage(); // Total Records in the db table:


/* Send the 3 variables to the Pagination class to be processed */
$pagination = new Pagination($current_page, $per_page, $total_count);


/* Grab the offset (page) location from using the offset method */
$offset = $pagination->offset();

/*
 * Grab the data from the CMS class method *static*
 * and put the data into an array variable.
 */
$cms = CMS::page($per_page, $offset);
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=yes, initial-scale=1.0">
    <title>Fan of LEGO</title>
    <link rel="stylesheet" media="all" href="assets/css/styles.css">
</head>
<body class="site">
<header class="headerStyle">
 
</header>
<?php include_once 'assets/includes/inc.navigation.php'; ?>
<section class="main">
    <?php
    foreach ($cms as $record) {

        echo '<header class="sectionHeader">';
        echo '<h2 class="sectionHeadingText">'. $record['heading'] . '</h2>';
        echo '</header>';
        echo '<article class="sectionArticle">';
        echo '<img class="imageArticle right-side" src="' . $record['image_path'] . '" alt="LEGO Bookstore">';
        echo '<p class="articleText">' . nl2br($record['content']). '</p>';
        echo ' </article>';
        echo '<footer class="sectionFooter">';
        echo '<p class="sectionText">Written by ' . $record['author'] . ' on ' . CMS::styleDate($record['date_added']) .' </p>';
        echo '</footer>';
    }
    ?>
</section>
<?php include_once "assets/includes/inc.sidebar.php" ?>
<?php include_once 'assets/includes/inc.footer.php'; ?>

</body>
</html>

You can see what data your form IS submitting by adding the following line of code near the start of your php code -

echo '<pre>'; print_r($_POST); echo '</pre>';
Sponsor our Newsletter | Privacy Policy | Terms of Service