PHP MySQL Insert Data

PHP Tutorial

PHP MySQL Insert Data

Below is a clear, step-by-step guide to PHP MySQL Insert Data, with real examples, security best practices, and error handling.


1️⃣ Database & Table Example

Assume you have this MySQL table:

CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
age INT
);

2️⃣ PHP–MySQL Connection (MySQLi)

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "testdb";
$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) {
die(“Connection failed: “ . $conn->connect_error);
}
?>


3️⃣ Simple INSERT Query (Not Recommended for Production)


 

⚠️ Problem: Vulnerable to SQL Injection


4️⃣ ✅ Secure Method (Prepared Statements – Recommended)


 

🔒 Why Prepared Statements?

  • Prevents SQL Injection

  • Faster for repeated inserts

  • Industry best practice


5️⃣ Insert Data from HTML Form

HTML Form

<form method="post">
Name: <input type="text" name="name"><br><br>
Email: <input type="email" name="email"><br><br>
Age: <input type="number" name="age"><br><br>
<button type="submit" name="save">Save</button>
</form>

PHP Code


 


6️⃣ Insert Multiple Records (Loop)

$users = [
["Ankit", "ankit@gmail.com", 24],
["Neha", "neha@gmail.com", 21],
["Ravi", "ravi@gmail.com", 26]
];
$stmt = $conn->prepare(
“INSERT INTO users (name, email, age) VALUES (?, ?, ?)”
);

foreach ($users as $u) {
$stmt->bind_param(“ssi”, $u[0], $u[1], $u[2]);
$stmt->execute();
}

echo “Multiple records inserted”;


7️⃣ Common Errors & Fixes

Error Reason Fix
Access denied Wrong DB credentials Check username/password
Table doesn't exist Table name wrong Verify table
Undefined index Form field missing Check input names
SQL Injection risk Raw queries Use prepared statements

8️⃣ Best Practices ✅

✔ Always use prepared statements
✔ Validate & sanitize user input
✔ Handle errors properly
✔ Close database connection

You may also like...