<?php
//Connect to database
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
//Insert data into table
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$query = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $db->prepare($query);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->execute();
}
//Read data from table
$query = "SELECT * FROM users";
$stmt = $db->prepare($query);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
//Update data in table
if(isset($_POST['edit'])){
$id = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];
$query = "UPDATE users SET name = :name, email = :email WHERE id = :id";
$stmt = $db->prepare($query);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':id', $id);
$stmt->execute();
}
//Delete data from table
if(isset($_POST['delete'])){
$id = $_POST['id'];
$query = "DELETE FROM users WHERE id = :id";
$stmt = $db->prepare($query);
$stmt->bindParam(':id', $id);
$stmt->execute();
}
?>
<!-- Display data in table -->
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user): ?>
<tr>
<td><?php echo $user['id']; ?></td>
<td><?php echo $user['name']; ?></td>
<td><?php echo $user['email']; ?></td>
<td>
<form method="POST">
<input type="hidden" name="id" value="<?php echo $user['id']; ?>">
<input type="text" name="name" value="<?php echo $user['name']; ?>">
<input type="email" name="email" value="<?php echo $user['email']; ?>">
<button type="submit" name="edit">Edit</button>
</form>
<form method="POST">
<input type="hidden" name="id" value="<?php echo $user['id']; ?>">
<button type="submit" name="delete">Delete</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<!-- Form to insert data -->
<form method="POST">
<input type="text" name="name" placeholder="Name">
<input type="email" name="email" placeholder="Email">
<button type="submit" name="submit">Add User</button>
</form>