User Tools

Site Tools


programmieren:html:forms

HTML Forms

1st Iteration

HTML forms done like dis in a PHP app for example:

<form action="form.php" method="post" id="message">
    Name: <input type="text" name="name"><br>
    E-mail: <input type="email" name="email"><br>
    <input type="submit">
</form>
 
<textarea name="message" form="message">Write message here...</textarea>

This leads to the textarea being below the submit button but still being part of the form since you can't put textareas as a form input.

Reading data from Form

Form needs to do a Post then the data can be read from the post like so:

<?= 'Name: ' . $_POST["name"] ?>
<br>
<?= 'Email: ' . $_POST["email"] ?>
<br>
<?= 'Phone: ' . $_POST["phone"] ?>
<br>
<?= 'Birthday: ' . $_POST["birthday"] ?>
<br>
<?= 'Message: ' . $_POST["message"] ?>

2nd Iteration

Added

htmlspecialchars()

around output so no special chars can be inserted.

Flash Messages

Yoooo I made flash messages, gotta put them in the session (cuz that stays across pages) then send the user back to the index and check in the index for flash messages.

form.php

foreach ($_POST as $key => $value) {
    if (empty($value)) {
        session_start();
        $_SESSION['validation_error'] = $key . " cannot be empty";
 
        header('Location: index.php');
        exit;
    }
}

index.php

<?php
session_start();
if (isset($_SESSION['validation_error'])): ?>
    <div style="color: red">
        <?= htmlspecialchars($_SESSION['validation_error']) ?>
    </div>
    <?php unset($_SESSION['validation_error']) ?>
<?php endif ?>

The validation rules I made:

if (strlen($post['name']) > 50) {
    session_start();
    $_SESSION['validation_error'] = "Name cannot be longer than 50 characters.";
 
    header('Location: index.php');
    exit;
}
 
if (!preg_match('/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/', $post['email']) || strlen($post['email']) > 50) {
    session_start();
    $_SESSION['validation_error'] = "Email needs to be a valid email address and no longer than 50 characters.";
 
    header('Location: index.php');
    exit;
}
 
if (!preg_match(
    '/^(\+?)(\d{2,4})(\s?)(-?)((\(0\))?)(\s?)(\d{2})(\s?)(-?)(\d{3})(\s?)(-?)(\d{2})(\s?)(-?)(\d{2})/',
    $post['phone']
)
|| strlen($post['phone']) > 20) {
    session_start();
    $_SESSION['validation_error'] = "Phone needs to be a valid phone number.";
 
    header('Location: index.php');
    exit;
}
 
if (!date_parse_from_format('Y-m-d', $post['birthday']) || $post['birthday'] > date('Y-m-d')) {
    session_start();
    $_SESSION['validation_error'] = "Birthday needs to be a date in the format {yyyy-mm-dd} and cannot be in the future.";
 
    header('Location: index.php');
    exit;
}
 
if (strlen($post['message']) > 500) {
    session_start();
    $_SESSION['validation_error'] = "Message cannot be longer than 500 characters.";
 
    header('Location: index.php');
    exit;
}

3rd Iteration

In the 3rd Iteration I simply added saving the data put into the form to the Database:

    public function savePostData($post): void
    {
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "form_exercise";
 
        $conn = new mysqli($servername, $username, $password, $dbname);
 
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
 
        $sql = "INSERT INTO entries (name, email, phone, birthday, message) VALUES (?, ?, ?, ?, ?)";
 
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $stmt->bind_param("sssss", $name, $email, $phone, $birthday, $message);
 
            $name = $post["name"];
            $email = $post["email"];
            $phone = $post["phone"];
            $birthday = $post["birthday"];
            $message = $post["message"];
 
            $stmt->execute();
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
 
        $stmt->close();
        $conn->close();
    }

And displaying all entries in the index as a list:

    public function displayAllEntries(): void
    {
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "form_exercise";
 
        $conn = new mysqli($servername, $username, $password, $dbname);
 
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
 
        $sql = "SELECT * FROM entries";
        $result = $conn->query($sql);
 
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                echo 'Name: ' . htmlspecialchars($row['name']) . '  -  Email: ' . htmlspecialchars($row['email']) . '  -  Phone: ' . htmlspecialchars($row['phone']) . '  -  Birthday: ' . htmlspecialchars($row['birthday']) . '  -  Message: ' . htmlspecialchars($row['message']) . "<br>";
            }
        } else {
            echo "0 results";
        }
    }

Mistakes

Code style:

  • Apperantly I had too much repetitive code
  • Making it object oriented was good

Functionality:

  • Apperantly it was just barely reached, no explanation as to why.
  • I couldve done better validation
  • I couldve displayed multiple validation messages for all that was wrong
  • I couldve used PHP native validation functions
  • I couldve positioned the Form better

Presenting:

  • I was unprepared
  • I didn't answer many questions
  • There were some incidents with the streaming so that was bad blegh
programmieren/html/forms.txt · Last modified: by admin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki