Here's the updated and safer version of the code:
<?php
// Assuming you have established the database connection in $con
if (isset($_GET['tanggal'])) {
// Sanitize the input to prevent SQL injection
$tanggal = mysqli_real_escape_string($con, $_GET['tanggal']);
// Construct the SQL query with proper date comparison
$sql = "DELETE FROM tb_absen_mingguan WHERE tanggal <= (CURRENT_DATE - INTERVAL 7 DAY) AND tanggal = '$tanggal';";
$del = mysqli_query($con, $sql);
if ($del) {
echo "<script>
alert('Data telah dihapus!');
window.location='?page=rekap&act=mingguan';
</script>";
} else {
echo "<script>
alert('Failed to delete data. Error: " . mysqli_error($con) . "');
window.location='?page=rekap&act=mingguan';
</script>";
}
}
?>
In the updated code, I've made the following changes:
Sanitized the $_GET['tanggal']
input using mysqli_real_escape_string
to prevent SQL injection attacks.
Changed the SQL query to use proper date comparison. We need to specify both conditions in the WHERE clause: tanggal <= (CURRENT_DATE - INTERVAL 7 DAY)
to ensure that the "tanggal" is older than 7 days from the current date and tanggal = '$tanggal'
to ensure that we are deleting records with a specific date.
Added an error handling message in case the deletion operation fails.
Always ensure you sanitize and validate user inputs before using them in SQL queries to prevent potential security vulnerabilities. Additionally, consider using prepared statements with parameter binding instead of manually escaping user inputs to further enhance security.