💾 Part 5: Delete data with PHP / HTML form

Deletion is really simple. You can delete anything you want, but make sure to specify it as accurately as possible.
Mostly, rows are deleted by ID number, but sometimes rows are deleted by other values as well (like if we want to delete records from where date range is between X and Y).

Now that we have comment form, let’s say we also want to delete some comments.
For deletion, we can use PHP syntax:

<?php 
mysqli_query($con, "DELETE FROM comments WHERE id = '$id'");
?>

Create a random new PHP file, make a database connection, and use this command.
Replace the ‘$id’ with an ID of a comment you’d want to delete.
Then, open that PHP file, and check if that row got deleted from your database.

Independent exercise

Let’s say we want a little admin area where we can choose from the dropdown, which comments we want to delete.
For that, we need to:

  1. Create an HTML form with two fields – a dropdown field and a submit button.
  2. For the first field, use <select> tag, and write a loop that would echo all the options.
    All the <option> fields should be printed inside a php while() loop.
  3. Second field is a submit button, with text “Delete comment”
  4. With PHP, check if the form has been submitted
  5. Write an if-statement, which checks if the form has been submitted
  6. For testing purposes, write a code, that would echo an ID of the comment you chose
  7. If you get the ID printed out, check from your database, if this was the corresponding comment with the ID you wanted to delete
  8. If it’s all correct, run the mysqli_query, where you replace the $id with posted comment id.

You can use this as an HTML template

Just populate the form with data from the database.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title></title>
</head>

<style>
	input[type='text'], input[type=email], select, textarea {
		outline: none;
		border: 1px solid #dadada;
		background-color: #f0f0f0;
		color: #000000;
		font-family: 'Arial';
		border-radius: 20px;
		padding: 10px 20px;
		font-size: 16px;
		display: block;
		margin-bottom: 15px;
		resize: none;
		width: 300px;
	}
	button {
		padding: 10px 20px;
		background-color: #000000;
		color: #FFFFFF;
		outline: none;
		border: 0;
		border-radius: 20px;
		font-size: 16px;
	}
	textarea {
		height: 60px;
	}

</style>
<body>
	<form action="" method="post">
		<select name="comments">
			<option value="1">First comment</option>
			<option value="2">Second comment</option>
			<option value="3">Third comment</option>
		</select>
		<button type="submit">Delete comment</button>
	</form>

</body>
</html>
Scroll to Top