<?php
// Database configuration
$host = 'localhost'; // MySQL server host
$dbname = 'connectivityDB'; // Database name
$username = 'kshitij'; // MySQL username
$password = 'Pass@123'; // MySQL password

try {
    // Create a connection
    $conn = new mysqli($host, $username, $password, $dbname);

    // Check the connection
    if ($conn->connect_error) {
        throw new Exception("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully<br>";

    // CRUD Operations

    // Create
    function createUser($conn, $name, $email) {
        $stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
        $stmt->bind_param("ss", $name, $email);
        if ($stmt->execute()) {
            echo "New user created successfully<br>";
        } else {
            echo "Error: " . $stmt->error . "<br>";
        }
        $stmt->close();
    }

    // Read
    function readUsers($conn) {
        $result = $conn->query("SELECT * FROM users");
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>";
            }
        } else {
            echo "No users found.<br>";
        }
    }

    // Update
    function updateUser($conn, $id, $name, $email) {
        $stmt = $conn->prepare("UPDATE users SET name = ?, email = ? WHERE id = ?");
        $stmt->bind_param("ssi", $name, $email, $id);
        if ($stmt->execute()) {
            echo "User updated successfully<br>";
        } else {
            echo "Error: " . $stmt->error . "<br>";
        }
        $stmt->close();
    }

    // Delete
    function deleteUser($conn, $id) {
        $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            echo "User deleted successfully<br>";
        } else {
            echo "Error: " . $stmt->error . "<br>";
        }
        $stmt->close();
    }

    // Example usage of CRUD operations
    createUser($conn, "John Doe", "john@example.com");
    createUser($conn, "Jane Smith", "jane@example.com");
    echo "<br>All Users:<br>";
    readUsers($conn);
    updateUser($conn, 1, "John Updated", "john.updated@example.com"); // Update user with ID 1
    echo "<br>All Users after update:<br>";
    readUsers($conn);
    deleteUser($conn, 2); // Delete user with ID 2
    echo "<br>All Users after deletion:<br>";
    readUsers($conn);

} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
} finally {
    // Close the connection
    if (isset($conn)) {
        $conn->close();
    }
}
?>

