← Back to Chapters

MySQL INSERT Statement

? MySQL INSERT Statement

? Quick Overview

The INSERT INTO statement in MySQL is used to insert new records into a table. You can insert data for specific columns or for all columns of a table. This is one of the most commonly used SQL operations in database-driven PHP applications.

? Key Concepts

  • Used to add new rows into a MySQL table
  • Can insert data into all columns or selected columns
  • Supports inserting multiple rows in a single query
  • Commonly used with PHP & MySQL integrations

⚙️ Syntax / Theory

The basic syntax for inserting data into a table is:

? View Code Example
-- Basic INSERT syntax
INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3);

? Code Example: Insert All Columns

This example inserts a new student record:

? View Code Example
-- Insert values into all specified columns
INSERT INTO students (name, age, grade)
VALUES ('John Doe', 21, 'B');

? Live Output / Explanation

A new row is added to the students table with the provided values. If the query executes successfully, MySQL returns a confirmation that one row was affected.

? Code Example: Insert Specific Columns

You can insert values into selected columns and allow others to use default values:

? View Code Example
-- Insert data while skipping columns with defaults
INSERT INTO students (name, grade)
VALUES ('Alice Smith', 'A');

? Interactive Concept (PHP + MySQL Flow)

The diagram below represents how a PHP application sends an INSERT query to MySQL:

? View Flow Example
// PHP sends SQL query to MySQL server
User Form ➜ PHP Script ➜ MySQL INSERT ➜ Data Stored

? Use Cases

  • User registration systems
  • Saving form data from PHP applications
  • Logging activities or transactions
  • Adding products, books, or records dynamically

✅ Tips & Best Practices

  • Ensure the number of columns matches the number of values
  • Use single quotes for string values
  • Insert multiple rows using comma-separated values
? View Code Example
-- Insert multiple rows in one query
INSERT INTO students (name, age, grade)
VALUES ('John Doe', 21, 'B'), ('Jane Doe', 22, 'A');

? Try It Yourself

  • Create a books table with title, author, price, and publication_date
  • Insert multiple records into the table
  • Test inserting data with default and NULL values
  • Try inserting records using PHP and MySQLi or PDO