0% found this document useful (0 votes)
13 views

CRUD_Operations_in_PHP

Uploaded by

bsf2101016
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

CRUD_Operations_in_PHP

Uploaded by

bsf2101016
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

CRUD Operations in PHP

CRUD stands for Create, Read, Update, and Delete, which are the basic operations for
managing data in a database. Below is a practical implementation of CRUD in PHP.

Step 1: Database Connection


Before performing any operation, connect to the database:

<?php
$conn = new mysqli("localhost", "root", "", "test_db");
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
?>

Step 2: Create (Insert Data)


Add new records to the database using an INSERT query:

<?php
$conn->query("INSERT INTO users (name, email) VALUES ('Alice', '[email protected]')");
?>

Explanation: The INSERT query adds a new record with the name "Alice" and the email
"[email protected]" to the users table.

Step 3: Read (Retrieve Data)


Retrieve and display records from the database using a SELECT query:

<?php
$result = $conn->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo "{$row['id']} - {$row['name']} - {$row['email']}<br>";
}
?>

Explanation: The SELECT query fetches all data from the users table. The while loop iterates
over the results and prints each row.

Step 4: Update (Modify Data)


Modify existing records in the database using an UPDATE query:
<?php
$conn->query("UPDATE users SET email = '[email protected]' WHERE id = 1");
?>

Explanation: The UPDATE query changes the email of the user with ID 1 to
'[email protected]'.

Step 5: Delete (Remove Data)


Remove records from the database using a DELETE query:

<?php
$conn->query("DELETE FROM users WHERE id = 1");
?>

Explanation: The DELETE query removes the record with ID 1 from the users table.

Step 6: Close the Connection


After performing the CRUD operations, close the database connection:

<?php
$conn->close();
?>

You might also like