Reputation: 1381
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
Upvotes: 4
Views: 43492
Reputation: 74217
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();
Upvotes: 8
Reputation: 3434
Add a GET
parameter to your link:
echo "<td><a href='delete.php?id='".$row['id']."'>Delete</a></td>";
Then catch it in your delete.php
query:
$id = $_GET['id'];
mysqli_query($con,"DELETE FROM student WHERE id='".$id."'");
Upvotes: -2