MySQL Insert Multiple
Multiple records can be inserted efficiently using a reusable prepared statement.
What is it?
Multiple records can be inserted efficiently using a reusable prepared statement.
Why do we use it?
This is useful for importing or creating several records.
How does it work?
Prepare once, bind variables and execute multiple times with different values.
Syntax
$stmt = $conn->prepare("INSERT ... VALUES (?,?)");
$stmt->bind_param("ss", $name, $email);
Example
<?php
$conn = new mysqli("localhost", "root", "", "aifa_php_lab");
$stmt = $conn->prepare("INSERT INTO students (name,email) VALUES (?,?)");
$stmt->bind_param("ss", $name, $email);
$name = "Aman";
$email = "aman@example.com";
$stmt->execute();
$name = "Riya";
$email = "riya@example.com";
$stmt->execute();
echo "Multiple students inserted";
?>
Example Explained
More Examples
Read an array of students and execute the same prepared statement inside foreach.
⚠️ Important Rules
Validate every record before insertion.
❌ Common Mistakes
Creating a separate SQL string for every record unnecessarily.
🌍 Real-World Use
Bulk imports and data migration.
📝 Practice Exercise
Insert five students using one prepared statement.
💻 Try It Yourself
Write and run this PHP lesson inside the AIFA Coding Lab.