← Back to Chapters

MySQL INSERT Multiple Rows

? MySQL INSERT Multiple Rows

? Quick Overview

In MySQL, you can insert multiple rows into a table in a single query by separating each set of values with commas. This approach is highly efficient and commonly used in PHP-based applications to reduce database calls.

? Key Concepts

  • Single INSERT statement can add many records
  • Each row is written inside parentheses
  • Rows are separated using commas
  • Frequently used with PHP and MySQL together

⚡ Syntax / Theory

? View Code Example
// General syntax for inserting multiple rows
INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3),
       (value1, value2, value3),
       (value1, value2, value3);

? Code Example: Inserting Multiple Students

? View Code Example
// Insert multiple student records in one query
INSERT INTO students (name, age, grade)
VALUES ('John Doe', 21, 'B'),
       ('Jane Smith', 22, 'A'),
       ('Alice Brown', 23, 'C');

? Live Output / Explanation

What Happens?

All three student records are inserted into the students table at once. MySQL treats each set of values as a separate row but executes the operation in a single database call.

? PHP + MySQL Example

? View Code Example
// PHP example using MySQLi to insert multiple rows
$sql = "INSERT INTO students (name, age, grade)
VALUES ('Bob White', 25, 'B'),
       ('Carol Green', 24, 'A'),
       ('David Black', 22, 'C')";

mysqli_query($conn, $sql);

? Visual Flow (How Data Inserts)

PHP Query MySQL Engine Table Rows

? Use Cases

  • Bulk user registration
  • Importing CSV or Excel data
  • Saving multiple form entries
  • Batch product insertion in e-commerce apps

✅ Tips & Best Practices

  • Always validate data before inserting
  • Use transactions for large inserts
  • Batch large datasets to avoid timeouts
  • Prefer prepared statements for dynamic data

? Try It Yourself

  • Create a products table with name, price, and stock
  • Insert 5 products using one INSERT query
  • Execute the query using PHP
  • Verify records using SELECT *