Lesson 7 of 8

Handling Web Requests

Learn to handle a form submission: read the input, save it to a and print safely. Frameworks do this for you, but it helps to see the plain version first.

PHP
<?php
// form.php — serve with: php -S localhost:8000
// $_GET  = query string params (?name=Ada)
// $_POST = submitted form fields

$name = $_POST['name'] ?? '';
?>
<!DOCTYPE html>
<html><body>
  <form method="post">
    <input name="name" placeholder="Your name">
    <button>Say hi</button>
  </form>

  <?php if ($name !== ''): ?>
    <!-- htmlspecialchars prevents XSS — ALWAYS escape output -->
    <p>Hello, <?= htmlspecialchars($name) ?>!</p>
  <?php endif; ?>
</body></html>
PHP
<?php
// PDO — PHP's built-in database layer (works with SQLite,
// MySQL, Postgres...). Prepared statements keep input as data:

$db = new PDO('sqlite:app.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->exec('CREATE TABLE IF NOT EXISTS guests
           (id INTEGER PRIMARY KEY, name TEXT)');

$stmt = $db->prepare('INSERT INTO guests (name) VALUES (?)');
$stmt->execute([$name]);

$rows = $db->query('SELECT name FROM guests')->fetchAll();
foreach ($rows as $row) {
    echo htmlspecialchars($row['name']), "<br>";
}
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.