How to Delete Data from Database with PHP & MySQL

PHP Delete Query Not Working? And error says ” Notice: Undefined Index: ID in C:\wamp64\Delete\table.php on line 48″?

Try to fix by doing this: First, you should assign primary key in your table in the database. And that primary key will be put in a hidden from input then put into the delete query.

Example below: Id is the primary key

<input type = "hidden" name = "Id" value = "<?php echo $row['Id'];?>"/>

Now, let’s make the delete query.



Source Code:

Note: Change the Database and table name before running the code

table.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel = "stylesheet" type = "text/css" href = "style.css"
</head>
<body>
    <h1>Delete Data</h1>
<div id = "container">
    <table>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
            <th>Action</th>
        </tr>
<?php

	$con = mysqli_connect('localhost','root','');
	mysqli_select_db($con, 'db_company');
	$select = " select * from tb_employee order by Id ASC";
	$result = mysqli_query($con, $select);
	while($row = $result->fetch_assoc()){
?>

        <tr>
            <td><?php echo $row['Id'];?></td>
            <td><?php echo $row['Name'];?></td>
            <td><?php echo $row['Age'];?></td>
            <td><?php echo $row['Country'];?></td>
	        <td>
		        <form action ="table.php" method = "POST">
                    <input type = "hidden" name = "Id" value = "<?php echo $row['Id'];?>"/>
                    <input type = "submit" class = "button"name = "delete" onclick= "return confirm ('DO YOU WANT TO DELETE?')"  value = "Delete" /> 
		        </form>
	        </td>
        </tr>
<?php
}
?>

<?php 

if (isset($_POST['delete'])){

	$Id = $_POST['Id'];
	$select = " delete from tb_employee where Id = '$Id'";
	$result = mysqli_query($con, $select);

    echo '<script type = "text/javascript">';
    echo 'alert("Deleted!");';
    echo 'window.location.href = "table.php" ';
    echo '</script>';

}

?>
</div>

</table>
</body>
</html>
style.css
body{
    margin: 20px;
}

#container{
    display: table;
    margin: 0 auto;

}

h1{
    text-align: center;
}

table {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    width: 100%;
    border-collapse: collapse;
}

td,
th {
    border: 1px solid darkgray;
    text-align: center;
    padding: 10px;
}

.button{
    cursor: pointer;
}

Leave a Comment

Your email address will not be published. Required fields are marked *