I'm a beginner in PHP and what I need to do is delete from my uploads folder as well as deleting a row of information in the database from phpMyAdmin. I know I have to implement an unlink, but I'm not sure how to place it in my code. Any help would be appreciated. Thank you.
$dbc = mysqli_connect('localhost', 'root', 'root', 'myimages');
$files = glob("uploads/*.*");
if (isset($_GET['id']) && is_numeric($_GET['id']) ) {
$query = "SELECT title FROM imagedata WHERE id={$_GET['id']}";
if ($r = mysqli_query($dbc, $query)) {
$row = mysqli_fetch_array($r);
print '<form action="delete_image.php" method="post">
<p style="color: red;">Are you sure you want to delete this image?</p>
<p><h4>' . $row['title'] . '</h4><br>
<input type="hidden" name="id" value="' . $_GET['id'] . '">
<input type="submit" name="submit" value="Delete this image"></p>
</form>';
} else {
print '<p style="color: red;">Could not retrieve the image because:<br>' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
} elseif (isset($_POST['id']) && is_numeric($_POST['id'])) {
$query = "DELETE FROM imagedata WHERE id={$_POST['id']} LIMIT 1";
$r = mysqli_query($dbc, $query);
if (mysqli_affected_rows($dbc) == 1) {
print '<p>The image has been deleted.</p>';
} else {
print '<p style="color: red;">Could not delete the image because:<br>' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
} else {
print '<p style="color: red;">This page has been accessed in error.</p>';
}
mysqli_close($dbc);
What column name do you use to store the file path? You will need to retrieve this as part of your first query:
$query = "SELECT title FROM imagedata WHERE id={$_GET['id']}";
Becomes:
$query = "SELECT title,path FROM imagedata WHERE id={$_GET['id']}";
And then you can use unlink()
just above the database query:
unlink( $row['path'] ); // if you store full path + filename
unlink( '/path/to/your/uploads/folder/here/' . $row['path'] ); // if you store just the file name and not folder
$query = "DELETE FROM imagedata WHERE id={$_POST['id']} LIMIT 1";
$r = mysqli_query($dbc, $query);