Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete a specific row of a table using php

I have designed a table that will display data something like this:

ID  name    Delete
1   abc     Delete
2   def     Delete

the code used for the above display is

<?php
$con=mysqli_connect("abc","abc","abc","abc");
// Check connection
if (mysqli_connect_errno()) 
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM student");
echo "<table class='table table-striped table-bordered table-hover'>
<thead>
<tr>
<th>ID</th>
<th>name</th>
<th>delete</th>   
</tr>
</thead>";
while($row = mysqli_fetch_array($result)) 
{
echo "<tbody data-link='row' class='rowlink'>";
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td><a href='delete.php'>Delete</a></td>";
echo "</tr>";
echo "</tbody>";    
}
echo "</table>";
mysqli_close($con);
?>

code for delete.php

<?php
$con=mysqli_connect("abc","abc","abc","abc");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"DELETE FROM student WHERE id='$id'");
mysqli_close($con);
header("Location: index.php");
?> 

View of database is

Id  name
1   abc
2   cdf

the problem is that it is not deleting the data and is also not showing any error

like image 284
Sam Avatar asked Oct 30 '25 11:10

Sam


1 Answers

Note that according to the HTTP standard, the GET method shouldn't be used for modifying data in the database. Therefore you should use a form with method="POST", like

echo '<td><form method="POST" action="delete.php"><input type="hidden" value="'.$row['id'].'"><input type="submit" value="Delete"></form></td>';

Then for delete.php, for safety purposes, you should look into using mysqli with prepared statements, or PDO with prepared statements, they much safer. I have included an example below.


Here is a prepared statements example:

<?php 
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_USER = "xxx";
$DB_PASS = "xxx";

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

$id = (int)$_POST['id'];

$update = $con->prepare("DELETE FROM student WHERE id = ?");
$update->bind_param('i', $id);
$update->execute();
like image 148
Funk Forty Niner Avatar answered Nov 01 '25 09:11

Funk Forty Niner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!