Logo  

CS479/579 - Web Programming II

Displaying exercises/e6/solution/mboard.php

<?php
  include "config.php";

  // Check if there was a new posting:
  if (isset($_POST['mesg'])) {
    $title = isset($_POST['title'])? htmlspecialchars($_POST['title']) : "";
    $mesg = htmlspecialchars($_POST['mesg']);

    // This locks the table so that only we can write to it:
    // not strictly necessary for this assignment:
    $myconn->query("LOCK TABLES `messages` WRITE") or die("lock" . $myconn->error);

    // Make the prepared insert statement:
    $stmt = $myconn->prepare("INSERT INTO `messages` (`title`, `mesg`) VALUES (?, ?)");
    if ($stmt == false) die("prepare" . $myconn->error);
    $stmt->bind_param("ss", $title, $mesg);

    $stmt->execute();
    $stmt->close();
    // Insure that the table is unlocked after we're done inserting the data:
    $myconn->query("UNLOCK TABLES") or die("unlock" . $myconn->error);
  }
?>
<!DOCTYPE html>
<html>
<head>
  <title> Messages </title>
  <meta charset=utf-8>
  <style>
  #m th { background: lightgray; font-size: 150%; }
  #m td { border-bottom: 1px solid gray; }
  pre { font-family: "Arial"; }
  </style>
</head>
<body>
 <h1> Assignment #5 </h1>
 <table id='m'>
<?php
  // This time lock tables for reading, a table can have an unlimited number of
  // reader locks, but only one write lock at any given time.  The reader lock
  // just guarantees that no one can write to the table while we're reading it.
  // I.e. no one can get a write lock while there are read locks.
  $myconn->query("LOCK TABLES `messages` READ") or die("lock" . $myconn->error);

  // Just iterate through all the messages:
  $res = $myconn->query("SELECT * FROM `messages`");
  $count = 0;
  // Fetch each row as an associative array:
  while ($mesg = $res->fetch_assoc()) {
      echo "<tr><th>{$mesg['title']}\n";
      echo "<tr><td><pre>{$mesg['mesg']}</pre>\n";
      $count++;
  }
  // Always unlock the table when you are done with it.  Don't assume this
  // happens automatically.
  $myconn->query("UNLOCK TABLES") or die("unlock" . $myconn->error);

  // If we didn't get anything from the select, print this message:
  if ($count == 0) {
    echo "<tr><td> No messages\n";
  }
?>
</table>
<hr>
Add message:
<form method=post>
<table>
 <tr> <td> Title: <td> <input type='text' name='title'>
 <tr> <td> Mesg: <td> <textarea name='mesg' cols=40 rows=10></textarea>
 <tr> <td colspan=2> <input type='submit'>
</table>
</form>
</body>
</html>