ckportfolio.com - Creating Database Entries with SQL INSERT

Creating Database Entries with SQL INSERT

HTML Form

We can now move onto creating a HTML form that can receive user input and submit to another script.

form.php

<form method="POST" action="post.php"> 
    <input type="text" name="title" placeholder="Title Area" required>
    <br>
    <textarea name="content" placeholder="Content Area" required></textarea>
    <br>
    <button>Submit</button>
</form>
  • <form> defines an area for user-provided data, with an ability to define how data is transmitted (POST), and where data will be transferred to (post.php).
  • <input> features type (type of form field), name (name that script.php will use to refer to provided data), and placeholder attributes.
  • Similarly, <textarea> features name and placeholder attributes, but not type as it assumes only one type.
  • Both fields feature required attribute, which disallows the user from proceeding until they are populated.
  • <button> serves as a default submission button, complete with area for label customization.

Upon populating the form and submitting to the database, the user data is pushed to post.php.

Post to Database

As the submitted data is pushed directly to post.php, we can move onto parsing this information and use SQL INSERT to create a new database row.

post.php is unique because this module is not designed to display information, but to process it and push the user back to index.php. We can start by including sql.php and creating new variables:

<?

    include "sql.php";
    $title = $_POST["title"];
    $content = $_POST["content"];

    echo $title;
    echo $content;

?>

Because we are looking to retrieve information from form submission (and not the address bar), we are using $_POST instead of $_GET, followed by column name that one wishes to pull up.

Upon verifying that both variables correctly display, we can remove placeholder echo commands and move onto constructing the SQL query.

<?

    include "sql.php";
    $title = $_POST["title"];
    $content = $_POST["content"];

    $query = "INSERT INTO posts (`title`, `content`) VALUES ('$title', '$content')";
    $result = $conn->query($query);
    header("Location: index.php");

?>

Note that the query variable now features INSERT INTO, followed by other necessary parameters:

  • posts: target table
  • (title, content): columns to be populated
  • VALUES ('$title', '$content') reference to variables above in alignment with target columns

Upon finishing this query, we are instructing the browser to return to index.php.

We can now confirm that the microblog is finished, complete with the following capabilities:

  • Ability to list all available entries
  • Ability to select a single article
  • Ability to post content to database
Fin