CRUD_Operations_in_PHP
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.
<?php
$conn = new mysqli("localhost", "root", "", "test_db");
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
?>
<?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.
<?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.
Explanation: The UPDATE query changes the email of the user with ID 1 to
'[email protected]'.
<?php
$conn->query("DELETE FROM users WHERE id = 1");
?>
Explanation: The DELETE query removes the record with ID 1 from the users table.
<?php
$conn->close();
?>