Let's Get Started with a PHP/MySQL Form Page!

  1. Open Notepad++
  2. Choose: File -> New
  3. Copy the PHP Form Template (PHP) code (below)
  4. Paste that code into your new file
  5. Change the put-title-of-this-page-here
  6. Change the lines with the blanks:
    $query  = "____________________________";
    $query .= "____________________________;";

    to:
    $query  = "INSERT INTO dishes (dish_name, price, is_spicy) ";
    $query .= "VALUES ('$name', $price, $isSpicy);";
  7. Click: File -> Save As
  8. Name your file: \www\mysqlform.php
  9. Change the Save as type: to: PHP Hypertext Preprocessor (*.php)
  10. Click: Save
  11. Visit your page (http://buffalo.edu/form.php) in your favorite web browser
  12. Make any changes
  13. Save your changes
  14. Fill in the form fields
  15. Submit your form
  16. View your mysqlform.php page to see if the addition worked
  17. Change: $debug = 0;
    to: $debug = 1;
  18. Add another record to see the debug messages

PHP Form Template (PHP)

<!doctype html>
<html>
  <head>
    <title>put-title-of-this-page-here</title>
  </head>
  <body>
  <?php 
$debug = 0;
if (isset($_POST['submit'])) {
  if ($debug) {
    foreach ($_POST as $postElement => $postValue) {
      echo("\$_POST[$postElement] = $postValue<br/>\n");
    }
  }
  $name    = $_POST['Name'];
  $price   = $_POST['Price'];
  $isSpicy = $_POST['isSpicy'];
  $dbUsername = "your-localhost-username"; // probably 'root'
  $dbPassword = "your-localhost-mysql-password"; // probably ''
  $dbDatabase = "mfc211"; // localhost database name
  $dbServer   = "localhost";
  // Create a new server connection
  $dbConn = new mysqli($dbServer, $dbUsername, $dbPassword, $dbDatabase);
  // Create the query
  $query  = "____________________________";
  $query .= "____________________________;";
  if ($debug) { echo("$query<br/>\n"); }
  // Send the query to MySQL
  $result = $dbConn->query($query,MYSQLI_STORE_RESULT);
  echo("$name ($price) record inserted!<br/>\n");
} 
?>
  <h1>My Dish Data Entry Form</h1>
    <form id="dishForm" method="POST" action="mysqlform.php">
      <fieldset> 
      <legend>Dish Information</legend> 
      <label for="Name">Name:</label> 
      <input id="Name" name="Name" type="text"/><br style="clear: both;"/> 
      <label for="Price">Price:</label> 
      <input id="Price" name="Price" type="text"/><br style="clear: both;"/>
      <label for="isSpicy">Is Spicy?</label>
      <Select id="isSpicy" name="isSpicy">
        <option value="1">Yes</option>
        <option value="0">No</option>
      </select><br style="clear: both;"/>
      </fieldset> 
      <label for="submit"></label>
      <button id="submit" name="submit" type="submit" 
      value="Do it!">Do it!</button><br style="clear: both;"/>
    </form>  
  </body>
</html>

Output