Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

4. Insert, Update & Delete

Lesson 30 of 36 in the free Web Based Programming notes on Siksha Sarovar, written by Rohit Jangra.

Database CRUD Operations: INSERT, UPDATE & DELETE

Study Deep: Preventing SQL Injection

SQL Injection is one of the most common web vulnerabilities. It occurs when malicious SQL code is inserted into a query via user input.

The Solution: Prepared Statements

  1. Prepare: The SQL template is sent to the server.
  2. Bind: User input is sent separately as parameters.
  3. Execute: The server combines them safely.

This ensures that even if a user enters ' OR '1'='1, it is treated as a literal string, not as part of the SQL command.

1. What is CRUD?

CRUD stands for the four fundamental operations performed on persistent data in any database-driven application:

LetterOperationSQL CommandDescription
CCreateINSERTAdd new records into a table
RReadSELECTRetrieve/fetch data from a table
UUpdateUPDATEModify existing records
DDeleteDELETERemove records from a table

Every web application (social media, e-commerce, banking) is essentially a series of CRUD operations.

2. INSERT — Adding Records

Full Syntax:

INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);

PHP Example — Insert a single record:

<?php
$conn = new mysqli("localhost", "root", "", "CollegeDB");

$name   = "Rohit Kumar";
$email  = "rohit@example.com";
$course = "BCA";
$marks  = 87.5;

$sql = "INSERT INTO students (name, email, course, marks)
        VALUES ('$name', '$email', '$course', $marks)";

if ($conn->query($sql) === TRUE) {
  echo "Record inserted! New ID: " . $conn->insert_id;
} else {
  echo "Error: " . $conn->error;
}
$conn->close();
?>
Note: $conn->insert_id returns the AUTO_INCREMENT ID of the last inserted row.

Insert Multiple Records at Once (Efficient):

$sql = "INSERT INTO students (name, course) VALUES
        ('Priya', 'BCA'),
        ('Amit', 'BCA'),
        ('Neha', 'BCA')";
$conn->query($sql);
echo "3 records inserted!";

3. Prepared Statements — Preventing SQL Injection

Definition: A Prepared Statement is a pre-compiled SQL template where user input is bound as parameters after the query is compiled. This completely prevents SQL Injection attacks.

WITHOUT Prepared Statements (VULNERABLE):

$name = $_POST['name']; // If user enters: ' OR '1'='1
$sql = "SELECT * FROM users WHERE name='$name'"; // SQL INJECTION! All records returned.

WITH Prepared Statements (SAFE):

<?php
$stmt = $conn->prepare("INSERT INTO students (name, email, course) VALUES (?, ?, ?)");
// 's' = string, 'd' = double/int, 'i' = integer
$stmt->bind_param("sss", $name, $email, $course);

$name   = "Rahul";
$email  = "rahul@email.com";
$course = "BCA";
$stmt->execute();

echo "Inserted safely! ID: " . $stmt->insert_id;
$stmt->close();
?>

4. UPDATE — Modifying Records

CRITICAL RULE: Always use WHERE with UPDATE. Without WHERE, every single row will be modified.

Syntax:

UPDATE table_name SET col1 = val1, col2 = val2 WHERE condition;

PHP Example — Update a specific student's marks:

<?php
$newMarks  = 92.0;
$studentId = 1;

$sql = "UPDATE students SET marks = $newMarks WHERE id = $studentId";

if ($conn->query($sql) === TRUE) {
  $affected = $conn->affected_rows; // How many rows were changed
  echo "Update successful! $affected row(s) modified.";
} else {
  echo "Error updating: " . $conn->error;
}
?>

Update Multiple Columns at Once:

$sql = "UPDATE students
        SET marks = 95.0, course = 'MCA'
        WHERE id = 2";
$conn->query($sql);

5. DELETE — Removing Records

CRITICAL RULE: Always use WHERE with DELETE. Without WHERE, the ENTIRE TABLE will be emptied.

Syntax:

DELETE FROM table_name WHERE condition;

PHP Example — Delete a specific student:

<?php
$studentId = 3;

$sql = "DELETE FROM students WHERE id = $studentId";

if ($conn->query($sql) === TRUE) {
  echo "Record deleted successfully! Rows affected: " . $conn->affected_rows;
} else {
  echo "Error deleting: " . $conn->error;
}
?>

Soft Delete Pattern (Best Practice): Instead of actually deleting, mark records as inactive. This preserves data history.

// Instead of DELETE, set is_active = 0
$sql = "UPDATE students SET is_active = 0 WHERE id = 3";
$conn->query($sql);
echo "Student deactivated (soft deleted).";

6. Summary Comparison of DML Operations

OperationSQLKey ConcernPHP Property
INSERTINSERT INTO ... VALUESReturns new AUTO_INCREMENT ID$conn->insert_id
UPDATEUPDATE ... SET ... WHEREAlways use WHERE!$conn->affected_rows
DELETEDELETE FROM ... WHEREAlways use WHERE!$conn->affected_rows