I have a code for retrieving question data inside my database and I have a action column for delete and edit, I dont have a code for edit but in delete, I want the delete to be function dynamically in all tables inside my database, and its not working, if I click delete and ok the page output is the else which is Invalid ID or table provided, anyone can help?
CODE FOR DELETE
<!DOCTYPE html>
<html lang="en"
<body>
<?php
$servername = "localhost";
$username = "root"; // Replace with your MySQL username
$password = ""; // Replace with your MySQL password
$dbname = "question_databank"; // Replace with your database name
if (isset($_GET['table']) && !empty($_GET['table'])) {
$table = $_GET['table'];
} else {
die("Table name not provided.");
}
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM $table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table>";
$row = $result->fetch_assoc();
echo "<tr>";
foreach ($row as $key => $value) {
echo "<th>$key</th>";
}
echo "<th>Action</th>";
echo "</tr>";
do {
echo "<tr>";
foreach ($row as $value) {
echo "<td>$value</td>";
}
echo '<td class="action-column">';
echo '<a class="edit" href="#" onclick="confirmEdit(' . $row['id'] . ')"><i class="fas fa-edit"></i></a>'; // Edit icon
echo '<a class="delete" href="#" onclick="confirmDelete(' . $row['id'] . ')"><i class="fas fa-trash-alt"></i></a>'; // Delete icon
echo '</td>'; // Delete icon
echo '</td>';
} while ($row = $result->fetch_assoc());
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
<script>
function confirmDelete(id) {
var result = confirm("Are you sure you want to delete this record?");
if (result) {
window.location.href = 'action/delete.php?id=' + id;
}
}
function confirmEdit(id) {
var result = confirm("Are you sure you want to edit this record?");
if (result) {
window.location.href = 'action/edit.php?id=' + id;
}
}
</script>
</body>
</html>
CODE FOR delete.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "question_databank";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_GET['id']) && isset($_GET['table']) && !empty($_GET['id']) && !empty($_GET['table'])) {
$id = $_GET['id'];
$table = $_GET['table'];
// Use mysqli_real_escape_string to prevent SQL injection
$id = mysqli_real_escape_string($conn, $id);
$table = mysqli_real_escape_string($conn, $table);
// Create a SQL query to delete the record
$sql = "DELETE FROM $table WHERE id = $id";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
} else {
echo "Invalid ID or Table provided";
}
$conn->close();
?>
For my delete button to function dynamically in all of the tables inside my database