PHP CRUD Example
// Database connection details
$host = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
// Create a connection to the database
$conn = new mysqli($host, $username, $password, $database);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// CREATE - Insert a new record
if (isset($_POST['create'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully!";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
}
// READ - Retrieve and display records
$result = $conn->query("SELECT * FROM users");
if ($result->num_rows > 0) {
echo "
Users
";echo "
- ";
- " . $row['name'] . " - " . $row['email'] . " ";
while ($row = $result->fetch_assoc()) {
echo "
}
echo "
} else {
echo "No users found.";
}
// UPDATE - Update an existing record
if (isset($_POST['update'])) {
$id = $_POST['id'];
$newName = $_POST['newName'];
$newEmail = $_POST['newEmail'];
$sql = "UPDATE users SET name='$newName', email='$newEmail' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully!";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
}
// DELETE - Delete a record
if (isset($_POST['delete'])) {
$id = $_POST['id'];
$sql = "DELETE FROM users WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully!";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
}
// Close the database connection
$conn->close();
?>