πŸ“– Saving Form Data and Redirecting in PHP MVC

🏁 Where You Left Off

  • register.php loads UserController::register()
  • The controller validates input and redisplays the form with any errors
  • The form lives at views/profile/create.php

🧠 Update the Controller with Redirect Logic

Modify the controller to call a model function when input is valid. On success, redirect the user to profile.php, which will show the new data.

<?php
require_once 'models/UserModel.php';

class UserController {
    public function register() {
        $post = ['name' => '', 'email' => ''];
        $errors = [];

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $post['name'] = trim($_POST['name'] ?? '');
            $post['email'] = trim($_POST['email'] ?? '');

            if ($post['name'] === '') {
                $errors['name'] = 'Name is required.';
            }

            if (!filter_var($post['email'], FILTER_VALIDATE_EMAIL)) {
                $errors['email'] = 'Please enter a valid email address.';
            }

            // If no errors, save to database
            if (empty($errors)) {
                // Call the model to create a new user
                $userId = UserModel::createUser($post);  // createUser() is defined in UserModel.php

                // Check if the user was created successfully
                if ($userId) {
                    // Redirect to the profile view with the new user ID
                    header("Location: profile.php?id=$userId");
                    exit;
                } else {
                    // If there was a database error, add to errors
                    // Reload views/profile/create.php with error
                    $errors['db'] = '❌ Failed to save user to database.';
                }
            }
        }

        require 'views/profile/create.php';
    }

    // Show user profile by ID
    // This method will be called by profile.php
    public static function show() {
        // Get the user ID from the query string
        $id = $_GET['id'] ?? null;
        if (!$id) {
            echo "No user ID specified.";
            return;
        }

        // Fetch user data from the model
        $user = UserModel::getUserById($id);
        if (!$user) {
            echo "User not found.";
            return;
        }

        require 'views/profile/show.php';
    }
}

πŸ’‘ Tip: Notice the syntax UserModel::createUser() β€” this is how we call a static method inside a class. Because our UserModel class uses public static function for its methods, we don’t need to create an object first. This keeps things simple and readable in smaller MVC-style projects.

πŸ—ƒοΈ Add the Model Functions

All database interactions should be defined in models/UserModel.php using PDO. This class-based structure ensures that your queries are reusable, secure, and separate from your controller logic. In this section, you’ll add methods to retrieve, update, and delete user records using prepared statements.

<?php
// UserModel.php
require_once 'db_connect.php';

class UserModel {
    protected static function getDB() {
        global $pdo;
        return $pdo;
    }

    public static function createUser($post) {
        $db = static::getDB();
        $sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
        $stmt = $db->prepare($sql);

        $success = $stmt->execute([
            ':name' => $post['name'],
            ':email' => $post['email'],
        ]);

        return $success ? $db->lastInsertId() : false;
    }

    public static function getUserById($id) {
        $db = static::getDB();
        $stmt = $db->prepare("SELECT * FROM users WHERE id = :id");
        $stmt->execute([':id' => $id]);

        return $stmt->fetch();
    }
}

This keeps database logic separate and secure using prepared statements.

πŸ‘οΈ Create the Profile View

Add a new file at views/profile/show.php to display the saved record:

<?php include 'views/partials/header.php'; ?>

<h3>User Profile</h3>

    <!-- Display user info from database -->
  <p><strong>Name:</strong> <?= htmlspecialchars($user['name']) ?></p>
  <p><strong>Email:</strong> <?= htmlspecialchars($user['email']) ?></p>

<?php include 'views/partials/footer.php'; ?>

This view is loaded by UserController::show() when profile.php?id=X is accessed.

πŸ“Œ Add the Profile Entry Point

Finally, create profile.php in the project root. This will be the default profile view request.

<?php
require_once 'controllers/UserController.php';
// Handle profile request
UserController::show();

βœ… Recap

  • Valid input is passed to createUser() and inserted into the database
  • On success, the user is redirected to profile.php?id=X
  • show() loads the profile data and displays it with views/profile/show.php

Last updated: August 6, 2025 at 4:48 PM