MySQL — Insert, Last ID, Multiple & Prepared
INSERT INTO adds new rows. Match column names to values. Never put raw user input directly into SQL strings.
Insert Data
INSERT INTO adds new rows. Match column names to values. Never put raw user input directly into SQL strings.
Real-life example: INSERT is adding a new contact to your phone — name, number, email in the right fields.
INSERT INTO students (name, email, score)
VALUES ('Asha Khan', 'asha@example.com', 88);<?php
$stmt = $pdo->prepare(
"INSERT INTO students (name, email, score) VALUES (:name, :email, :score)"
);
$stmt->execute([
":name" => "Ravi Patel",
":email" => "ravi@example.com",
":score" => 92,
]);
?>Get Last Insert ID
After INSERT, lastInsertId() returns the AUTO_INCREMENT id of the new row — useful for linking related records.
Real-life example: Last ID is the ticket number printed after you join a queue — you need it for the next step.
<?php
$stmt = $pdo->prepare("INSERT INTO students (name, email) VALUES (?, ?)");
$stmt->execute(["Asha", "asha@example.com"]);
$newId = $pdo->lastInsertId();
echo "New student ID: $newId";
?>Insert Multiple & Prepared Statements
Insert many rows with multiple VALUES or a loop. Prepared statements bind placeholders (? or :name) to prevent SQL injection.
Real-life example: Prepared statements are sealed envelopes — the post office knows the slot size; attackers cannot slip in extra instructions.
INSERT INTO students (name, email, score) VALUES
('Asha', 'a@ex.com', 88),
('Ravi', 'r@ex.com', 92),
('Meera', 'm@ex.com', 85);<?php
$stmt = $pdo->prepare("INSERT INTO courses (title, level) VALUES (:title, :level)");
foreach ([["PHP", "beginner"], ["MySQL", "intermediate"]] as [$t, $l]) {
$stmt->execute([":title" => $t, ":level" => $l]);
}
?>