PHP CHAPTER 33

MySQL Insert Data

INSERT adds a new record to a database table.

📘

What is it?

INSERT adds a new record to a database table.

💡

Why do we use it?

It saves form submissions and new application records.

⚙️

How does it work?

PHP sends an INSERT query to MySQL with values for selected columns.

🧩

Syntax

PHP Syntax
INSERT INTO students (name,email) VALUES (?,?);
💻

Example

PHP Example
<?php

$conn = new mysqli("localhost", "root", "", "aifa_php_lab");

$name = "Aman";
$email = "aman@example.com";

$stmt = $conn->prepare("INSERT INTO students (name,email) VALUES (?,?)");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();

echo "Student Inserted";

?>
🔍

Example Explained

prepare creates a parameterized query. bind_param attaches values. execute sends the query to MySQL.
🚀

More Examples

Insert course, phone and city fields using another prepared statement.

⚠️ Important Rules

Use prepared statements for user-provided data.

❌ Common Mistakes

Directly joining user input into SQL.

🌍 Real-World Use

Registration, admission, orders and student management.

📝 Practice Exercise

Create an Add Student PHP form connected to MySQL.

💻 Try It Yourself

Write and run this PHP lesson inside the AIFA Coding Lab.

Open Coding Lab →