10. CRUD Operation In PHP

10. CRUD Operation In PHP

CRUD (Create, Read, Update, Delete) operations in PHP using MySQL database:

  1. Create (INSERT):
// Establish a database connection
$connection = mysqli_connect('localhost', 'username', 'password', 'database_name');

// Prepare data for insertion
$name = 'John Doe';
$email = 'john@example.com';
$age = 25;

// Create a SQL query for insertion
$query = "INSERT INTO users (name, email, age) VALUES ('$name', '$email', $age)";

// Execute the query
mysqli_query($connection, $query);

// Close the database connection
mysqli_close($connection);
  1. Read (SELECT):
// Establish a database connection
$connection = mysqli_connect('localhost', 'username', 'password', 'database_name');

// Create a SQL query for selection
$query = "SELECT * FROM users";

// Execute the query
$result = mysqli_query($connection, $query);

// Fetch and display the data
while ($row = mysqli_fetch_assoc($result)) {
    echo "Name: " . $row['name'] . "<br>";
    echo "Email: " . $row['email'] . "<br>";
    echo "Age: " . $row['age'] . "<br><br>";
}

// Close the database connection
mysqli_close($connection);
  1. Update (UPDATE):
// Establish a database connection
$connection = mysqli_connect('localhost', 'username', 'password', 'database_name');

// Prepare data for update
$id = 1;
$newEmail = 'new_email@example.com';

// Create a SQL query for update
$query = "UPDATE users SET email='$newEmail' WHERE id=$id";

// Execute the query
mysqli_query($connection, $query);

// Close the database connection
mysqli_close($connection);
  1. Delete (DELETE):
// Establish a database connection
$connection = mysqli_connect('localhost', 'username', 'password', 'database_name');

// Prepare data for deletion
$id = 1;

// Create a SQL query for deletion
$query = "DELETE FROM users WHERE id=$id";

// Execute the query
mysqli_query($connection, $query);

// Close the database connection
mysqli_close($connection);

Note: It's important to sanitize and validate user inputs to prevent SQL injection and other security vulnerabilities. Consider using prepared statements or parameterized queries for safer database operations.

Also, make sure to replace 'localhost', 'username', 'password', 'database_name' with your actual database credentials and database name.