0% complete

PHP & MySQL · Lesson 4 of 11

Creating Tables

Define columns, keys, and constraints to protect data integrity.

Lesson

A table schema documents allowed data and enforces integrity. Use appropriate types, NOT NULL for required values, unique indexes for uniqueness, and foreign keys for relationships. Schema changes should be versioned so every environment can be migrated consistently. The example adds an index to support a common lookup by user email. Further guidance Use migrations to version schema changes, constraints to protect relationships, and prepared statements for every dynamic value. Scope writes with a precise condition, check affected rows, and use transactions when multiple statements must succeed together. Store credentials outside source control. Practice task: Create a fresh example for Creating Tables. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.

Code examples

Creating Tables
SQL
CREATE TABLE profiles (
    id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    user_id BIGINT UNSIGNED NOT NULL UNIQUE,
    display_name VARCHAR(100) NOT NULL,
    FOREIGN KEY (user_id) REFERENCES users(id)
);
Expected output
A profile table with one profile per user

Key points

  • Define columns, keys, and constraints to protect data integrity.
  • Use prepared statements for values and constraints for data integrity.
  • Scope writes carefully and verify their result.

Your learning progress

Finish this lesson

Optional practice

PHP playground

This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.

Execution is disabled. No code is sent to a server.