0
0
PHPprogramming~5 mins

Insert, update, delete operations in PHP

Choose your learning style9 modes available
Introduction

These operations let you add, change, or remove data in a database. They help keep your data up to date and useful.

When you want to add a new user to a website.
When you need to change a user's email address.
When you want to remove a product that is no longer available.
When updating stock quantities after a sale.
When cleaning up old or incorrect records.
Syntax
PHP
<?php
// Insert
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2');";

// Update
$sql = "UPDATE table_name SET column1 = 'value1' WHERE condition;";

// Delete
$sql = "DELETE FROM table_name WHERE condition;";
?>

These are SQL commands used inside PHP to work with databases.

Always use a WHERE clause in update and delete to avoid changing all rows.

Examples
Adds a new user named Alice with her email.
PHP
<?php
// Insert a new user
$sql = "INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')";
Changes Alice's email to a new one.
PHP
<?php
// Update user's email
$sql = "UPDATE users SET email = 'newemail@example.com' WHERE name = 'Alice'";
Removes the user named Alice from the database.
PHP
<?php
// Delete a user
$sql = "DELETE FROM users WHERE name = 'Alice'";
Sample Program

This program connects to a MySQL database, inserts a user named Bob, updates his email, then deletes him. It prints messages to show each step worked.

PHP
<?php
// Connect to database
$mysqli = new mysqli('localhost', 'user', 'password', 'testdb');
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}

// Insert a new record
$insert_sql = "INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com')";
if ($mysqli->query($insert_sql) === TRUE) {
    echo "Insert successful\n";
} else {
    echo "Insert error: " . $mysqli->error . "\n";
}

// Update the record
$update_sql = "UPDATE users SET email = 'bob.new@example.com' WHERE name = 'Bob'";
if ($mysqli->query($update_sql) === TRUE) {
    echo "Update successful\n";
} else {
    echo "Update error: " . $mysqli->error . "\n";
}

// Delete the record
$delete_sql = "DELETE FROM users WHERE name = 'Bob'";
if ($mysqli->query($delete_sql) === TRUE) {
    echo "Delete successful\n";
} else {
    echo "Delete error: " . $mysqli->error . "\n";
}

$mysqli->close();
OutputSuccess
Important Notes

Always check for errors after running SQL commands.

Use prepared statements to protect against SQL injection in real projects.

Remember to close the database connection when done.

Summary

Insert adds new data to a table.

Update changes existing data based on a condition.

Delete removes data based on a condition.