Insert, Update, Delete Data in MySQL with PHP

Learn how to insert, update, and delete MySQL records with PHP using clear examples for basic CRUD database operations.

Insert, Update, Delete Data in MySQL with PHP cover image

Learn how to manipulate MySQL database records using PHP and PDO securely and efficiently.

When I started building dynamic web applications with PHP, one of the first essential skills I had to master was working with a MySQL database. No matter if I was building a simple blog, an admin dashboard, or a SaaS platform, everything revolved around storing and manipulating data. That is where CRUD operations come in: Create, Read, Update, and Delete. In this article, I will walk through how I handle insert, update, and delete operations in PHP using PDO, while keeping the code secure, clean, and production-ready.

Why CRUD Operations Matter in PHP and MySQL Applications

CRUD stands for Create, Read, Update, and Delete. These are the four core database operations behind almost every modern web application. Whenever a user registers, updates their profile, publishes content, or removes data, a CRUD operation is executed in the background.

In PHP applications, MySQL is one of the most widely used database systems. To communicate with MySQL securely and efficiently, I prefer using PDO (PHP Data Objects). PDO provides a consistent interface for database access and, most importantly, supports prepared statements, which are critical for preventing SQL injection attacks.

Using PDO with prepared statements is not optional in modern PHP development. It is the baseline for secure database communication.

Connecting to MySQL with PDO

Before performing any insert, update, or delete operation, I first establish a secure database connection using PDO. The connection typically looks like this:

<?php
$pdo = new PDO("mysql:host=localhost;dbname=demo", "user", "pass", [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
?>

I always enable PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION so that database errors are thrown as exceptions. This makes debugging easier and allows proper error handling in production environments.

How I Insert Data into MySQL Using PHP PDO

Inserting data into a MySQL table is one of the most common operations. For example, when creating a new user record, I use a prepared statement with named parameters:

<?php
$stmt = $pdo->prepare("INSERT INTO users (username, email) 
                       VALUES (:username, :email)");

$stmt->execute([
    'username' => 'john_doe',
    'email'    => '[email protected]'
]);

echo "Data inserted successfully.";
?>

I avoid directly injecting variables into SQL queries. Instead, I bind values using placeholders like :username and :email. This approach protects the application from SQL injection and ensures that user input is handled safely.

In production systems, I also validate and sanitize user input before executing the query. Database security does not start at the query level; it starts at input validation.

Updating Existing Records Securely

Updating data is just as important as inserting it. For example, when a user changes their email address, I perform an update operation like this:

<?php
$stmt = $pdo->prepare("UPDATE users 
                       SET email = :email 
                       WHERE username = :username");

$stmt->execute([
    'username' => 'john_doe',
    'email'    => '[email protected]'
]);

echo "Data updated successfully.";
?>

One thing I always pay attention to is the WHERE clause. Without it, an UPDATE statement can accidentally modify every row in the table. I also sometimes check how many rows were affected:

<?php
if ($stmt->rowCount() > 0) {
    echo "Record updated.";
} else {
    echo "No changes made.";
}
?>

This helps me confirm whether the operation actually changed any data.

Deleting Records from a MySQL Database

Deleting data is powerful and potentially dangerous. Because of that, I treat DELETE operations with extra caution. Here is a simple example:

<?php
$stmt = $pdo->prepare("DELETE FROM users 
                       WHERE username = :username");

$stmt->execute([
    'username' => 'john_doe'
]);

echo "Data deleted successfully.";
?>

In real-world applications, I often implement soft deletes instead of permanent deletions. Instead of removing the record entirely, I update a column like deleted_at with a timestamp. This allows data recovery and improves auditability.

For sensitive systems, logging delete and update operations is just as important as executing them.

Best Practices for Secure PHP CRUD Operations

Over time, I developed a consistent set of best practices when working with PHP and MySQL:

Use prepared statements: Never build raw SQL queries with concatenated user input.

Validate and sanitize input: Always verify user data before sending it to the database.

Handle exceptions properly: Use try-catch blocks around database operations in production environments.

Use transactions when needed: If multiple queries must succeed together, wrap them in a transaction to maintain data integrity.

Limit database permissions: The database user should only have the permissions required for the application to function.

Final Thoughts on PHP PDO and MySQL CRUD

Working with MySQL in PHP becomes straightforward once CRUD operations are clearly understood. By using PDO and prepared statements, I ensure that my insert, update, and delete operations are both secure and efficient. These database operations form the backbone of almost every PHP-driven web application, from small personal projects to enterprise platforms.

Mastering secure CRUD operations is not just about writing functional code. It is about writing maintainable, scalable, and secure backend logic. Once I fully understood how to properly interact with MySQL using PDO, building dynamic features became significantly easier and far more reliable.