PHP MySQL Insert Data: Step-by-Step Guide with Code Examples and Best Practices
Last updated 3 months, 3 weeks ago | 339 views 75 5

Introduction: Why PHP MySQL Insert Data Is Essential
When building dynamic websites or applications, data entry is one of the most fundamental tasks. Whether it's a registration form, product details, or contact messages—inserting data into a MySQL database using PHP is the core mechanism behind it.
By learning how to securely insert data, you:
-
Power up features like user signup, blog publishing, and payment records
-
Understand how the backend interacts with stored information
-
Reduce risk of vulnerabilities like SQL injection
This guide walks you through how to insert data into a MySQL table using both MySQLi and PDO—with full working examples and best practices.
Prerequisites
Before inserting data, you should have:
-
PHP installed (version 7.4+ recommended)
-
A MySQL server running locally or remotely
-
A MySQL database and table ready
-
A working PHP environment like XAMPP/WAMP
If you don’t yet have a table, you can create one using PHP.
PHP Methods for Inserting Data into MySQL
PHP supports two main extensions to interact with MySQL:
Feature | MySQLi | PDO |
---|---|---|
DB Compatibility | MySQL only | Multiple DB engines |
Syntax Style | Procedural & Object-Oriented | Object-Oriented only |
Prepared Stmts | ✅ Yes | ✅ Yes |
Recommended For | Simple projects | Scalable, secure applications |
Method 1: Insert Data Using PHP MySQLi
Step-by-Step Example
<?php
// Step 1: Database credentials
$host = "localhost";
$user = "root";
$password = "";
$dbname = "test_db";
// Step 2: Create connection
$conn = new mysqli($host, $user, $password, $dbname);
// Step 3: Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Step 4: Prepare insert SQL
$name = "John Doe";
$email = "[email protected]";
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
// Step 5: Execute the query
if ($conn->query($sql) === TRUE) {
echo "New record inserted successfully!";
} else {
echo "Error: " . $conn->error;
}
// Step 6: Close connection
$conn->close();
?>
⚠️ Security Note: Avoid directly inserting user input like this in real-world apps. Use prepared statements instead.
Secure Insertion Using Prepared Statements (MySQLi)
<?php
$conn = new mysqli("localhost", "root", "", "test_db");
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
// Sample values
$name = "Alice";
$email = "[email protected]";
$stmt->execute();
echo "Record inserted securely!";
$stmt->close();
$conn->close();
?>
Method 2: Insert Data Using PHP PDO
Basic Insert Using PDO
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=test_db", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users (name, email) VALUES ('Bob', '[email protected]')";
$pdo->exec($sql);
echo "New record created successfully!";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
Secure Insert with PDO & Prepared Statements
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=test_db", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
// Bind values
$name = "Charlie";
$email = "[email protected]";
$stmt->execute();
echo "Secure insert successful!";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
✅ PDO is preferred for larger applications due to its flexibility, named placeholders, and robust error handling.
Complete Functional Example: Form to MySQL
<?php
// Connect
$conn = new mysqli("localhost", "root", "", "form_db");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get data from a sample form (e.g., POST)
$name = $_POST['name'];
$email = $_POST['email'];
// Prepare and bind
$stmt = $conn->prepare("INSERT INTO contacts (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
// Execute
if ($stmt->execute()) {
echo "Contact saved successfully!";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
$conn->close();
?>
Tips & Common Pitfalls
✅ Best Practices
-
Always use prepared statements to avoid SQL injection.
-
Validate and sanitize all user input.
-
Store DB credentials securely, not in public-facing code.
-
Use
mysqli_error()
orPDOException
to debug errors. -
Ensure the table exists before inserting data.
❌ Common Mistakes
Mistake | Solution |
---|---|
Inserting unsanitized data | Use filter_var() or prepared statements |
No error handling | Implement proper if checks or try/catch blocks |
Wrong table or column names | Double-check spelling and structure |
Missing connection close | Use $conn->close() or let PDO auto-close |
Summary Table: Insert Comparison
Feature | MySQLi | PDO |
---|---|---|
Basic Insert | query() |
exec() |
Secure Insert | prepare() + bind_param() |
prepare() + bindParam() |
Error Handling | Manual ($conn->error ) |
Exception-based (try/catch ) |
Portability | ❌ MySQL only | ✅ Multiple databases |
Conclusion: Final Thoughts & What’s Next
Inserting data into a MySQL database is the foundation of dynamic web applications. Whether you're creating a user login system, saving form inputs, or storing orders—this is a skill every PHP developer must master.
Key Takeaways
-
Use MySQLi or PDO to insert data into MySQL.
-
Prepared statements are essential for security.
-
Always validate and sanitize user inputs.
-
PDO is more robust and flexible for larger projects.