Sam Sam - 3 months ago 13
SQL Question

delete a specific row of a table using php

The question is very basic and i found many similar questions in stackoverflow but none of them worked properly for me.

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

I am new to this field, would be grateful if someone could help me

Answer

Change this line:

echo "<td><a href='delete.php'>Delete</a></td>";

to

echo "<td><a href=\"delete.php?id=".$row['id']."\">Delete</a></td>";

Then for delete.php (and as originally stated in a comment, $id was not defined).

<?php
$con=mysqli_connect("abc","abc","abc","abc");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$id = $_GET['id']; // $id is now defined

// or assuming your column is indeed an int
// $id = (int)$_GET['id'];

mysqli_query($con,"DELETE FROM student WHERE id='".$id."'");
mysqli_close($con);
header("Location: index.php");
?> 

and it will work.

Yet, 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";

$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
  die('Connection failed [' . $con->connect_error . ']');
}

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

$update = $con->prepare("DELETE FROM student WHERE id = ?");
$update->bind_param('i', $id);
$update->execute();
$update->close();