Delete Data using PHP & MySQL Database
Introduction
Deleting data from a MySQL database is a common operation in web development. In this guide, we will demonstrate how to perform this task using core PHP. The tutorial incorporates SEO best practices to ensure high visibility for related searches.
Prerequisites
- Basic understanding of PHP and MySQL.
- A MySQL database with a table containing data.
- A web server (e.g., XAMPP, WAMP, or a live server) to execute PHP scripts.
Steps to Delete Data in MySQL
1. Create a Database and Table
Run the following SQL commands to create a database and populate it with sample data:
CREATE DATABASE demo_db; USE demo_db; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL, age INT NOT NULL ); INSERT INTO users (name, email, age) VALUES ('John Doe', 'john.doe@example.com', 25), ('Jane Smith', 'jane.smith@example.com', 30);
2. Establish a Database Connection in PHP
<?php // Database connection settings $host = 'localhost'; $user = 'root'; $password = ''; // Use your database password $database = 'demo_db'; // Create connection $conn = new mysqli($host, $user, $password, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
3. Display Data with a Delete Option
<?php include 'db_connection.php'; // Fetch all users from the database $sql = "SELECT * FROM users"; $result = $conn->query($sql); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Delete User</title> <meta name="description" content="Learn how to delete data using PHP and MySQL with this practical example."> </head> <body> <h2>User List</h2> <table border="1"> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>Age</th> <th>Action</th> </tr> <?php while ($row = $result->fetch_assoc()) { ?> <tr> <td><?php echo $row['id']; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['email']; ?></td> <td><?php echo $row['age']; ?></td> <td> <a href="delete.php?id=<?php echo $row['id']; ?>" onclick="return confirm('Are you sure you want to delete this record?');">Delete</a> </td> </tr> <?php } ?> </table> </body> </html>
4. Handle the Delete Request in PHP
Create a file named delete.php
to process the delete action:
<?php // Include the database connection file include 'db_connection.php'; // Get the ID from the URL $id = $_GET['id']; // Prepare the SQL query to delete data $sql = "DELETE FROM users WHERE id = ?"; $stmt = $conn->prepare($sql); $stmt->bind_param("i", $id); // Execute the query if ($stmt->execute()) { echo "Record deleted successfully."; } else { echo "Error deleting record: " . $conn->error; } // Close the connection $stmt->close(); $conn->close(); // Redirect to the main page header("Location: index.php"); exit(); ?>
0 Replies to “Delete Data Using PHP & MySql Database”
Leave a Reply
Your email address will not be published.