如何从 PHP 中的文件夹中删除图像并从 phpMyAdmin 中删除文件名?

How to delete an image from folder in PHP and delete file name from phpMyAdmin?

我是 PHP 的初学者,我需要做的是从我的上传文件夹中删除以及从 phpMyAdmin 中删除数据库中的一行信息。我知道我必须实现取消链接,但我不确定如何将它放入我的代码中。任何帮助,将不胜感激。谢谢。

$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);

你用什么列名来存储文件路径?您需要在第一次查询时检索它:

$query = "SELECT title FROM imagedata WHERE id={$_GET['id']}";

变为:

$query = "SELECT title,path FROM imagedata WHERE id={$_GET['id']}";

然后你可以在数据库查询上面使用unlink()

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); 

如果你知道文件的名称,你可以试试

unlink($file); 

这是在您将其从您的数据库中删除之后

然后打印已删除消息