Insert, Update, Delete Data in MySQL with PHP
Learn how to manipulate MySQL database records using PHP and PDO securely and efficiently.
๐งฉ Why Learn CRUD Operations?
CRUD stands for Create, Read, Update, and Delete โ the four basic functions of persistent storage. In PHP, performing these actions with a MySQL database is essential for building dynamic applications.
๐ Insert Data
<?php
$pdo = new PDO("mysql:host=localhost;dbname=demo", "user", "pass");
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
$stmt->execute([
'username' => 'john_doe',
'email' => '[email protected]'
]);
echo "Data inserted successfully.";
?>
๐ Update Data
<?php
$stmt = $pdo->prepare("UPDATE users SET email = :email WHERE username = :username");
$stmt->execute([
'username' => 'john_doe',
'email' => '[email protected]'
]);
echo "Data updated successfully.";
?>
๐๏ธ Delete Data
<?php
$stmt = $pdo->prepare("DELETE FROM users WHERE username = :username");
$stmt->execute(['username' => 'john_doe']);
echo "Data deleted successfully.";
?>
โ Best Practices
- Use prepared statements to avoid SQL injection
- Always validate and sanitize user input
- Check affected rows with
rowCount()
if needed - Log changes if you're performing sensitive updates or deletions
๐งพ Summary
Performing insert, update, and delete operations in PHP using PDO is both secure and efficient. These CRUD operations are the backbone of most PHP-based web applications. Mastering them is key to becoming a confident backend developer.