Inserting new record rows into a database table is performed using SQL INSERT INTO statements executed via PDO prepared statements.
flowchart LR
A["Prepare SQL Statement"] -->|'$pdo->prepare()'|| B["Bind Named Parameters"]
B -->|'$stmt->execute()'|| C["Insert Row into Database"]
<?php
declare(strict_types=1);
try {
$pdo = new PDO("mysql:host=127.0.0.1;dbname=ecommerce_db;charset=utf8mb4", 'root', 'secret_password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
// Prepared SQL query template with named placeholders
$sql = "INSERT INTO users (username, email, status) VALUES (:username, :email, :status)";
$stmt = $pdo->prepare($sql);
// Bind values and execute
$userData = [
'username' => 'maksudur_dev',
'email' => '[email protected]',
'status' => 'active'
];
$stmt->execute($userData);
echo "User record inserted successfully!
";
} catch (PDOException $e) {
die("Insert Error: " . $e->getMessage());
}
"INSERT INTO users VALUES ('$name')"), which creates severe SQL Injection vulnerabilities.:username): Named parameters make complex queries readable and maintainable.PDOException: Handle duplicate key constraint violations (1062 Duplicate entry) gracefully.Write a SQL INSERT INTO template using named parameters :title and :price!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.