Ya, cukup sertakan logika hapus di atas pernyataan pilihan Anda.
<?php
// Connect to server and select database.
$link = mysqli_connect("localhost", "root", "password", "testdelete"); //for local machine testing
// Check connection
if ($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Handle delete
if (isset($_GET['delete_id'])) {
// get value of id that sent from address bar
$delete_id = (int) $_GET['delete_id'];
// Delete data in mysql from row that has this id
$sql="DELETE FROM testdelete.test_mysql WHERE id='$delete_id'";
$result=$link->query($sql);
// if successfully deleted
if ($result){
echo "Deleted Successfully";
echo "<BR>";
} else {
echo "Delete ERROR";
}
}
// select record from mysql
$sql = "SELECT id, name, lastname, email FROM testdelete.test_mysql";
$result = $link->query($sql);
if ($result->num_rows > 0) {
include 'table_header.html';
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td bgcolor=\"#FFFFFF\">".$row["id"]."</td>";
echo "<td bgcolor=\"#FFFFFF\">". $row["name"]."</td>";
echo "<td bgcolor=\"#FFFFFF\">" . $row["lastname"]."</td>";
echo "<td bgcolor=\"#FFFFFF\">". $row["email"] . "</td>";
echo "<td bgcolor=\"#FFFFFF\"><a href=\"?delete_id={$row['id']}\">Delete row</a></td>";
echo "</tr>";
}
include 'table_footer.html';
} else {
echo "0 results";
}
// close connection
mysqli_close($link);
?>
Namun, berhati-hatilah dengan pendekatan ini. Karena ini hanya tautan, dan jika bersifat publik, bot dapat merayapi dan menghapus semuanya.
Juga, perhatikan bahwa ada beberapa perubahan lain. Saya mengubah param dari id
untuk delete_id
, hanya untuk menghindari ambiguitas. Saya memperbarui tautan hapus. Saya sedang memeriksa $_GET['delete_id']
diatur sebelum menjalankan kueri penghapusan. Dan, saya melakukan casting (int) di $_GET['delete_id']
untuk memastikan itu benar-benar bilangan bulat.