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

时间:2017-03-02 18:19:49

标签: php phpmyadmin unlink

我是PHP的初学者,我需要做的是从我的uploads文件夹中删除以及从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);

2 个答案:

答案 0 :(得分:3)

您使用什么列名来存储文件路径?您需要在第一次查询中检索此内容:

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

答案 1 :(得分:1)

如果您拥有该文件的名称,您可以尝试类似

的内容
unlink($file); 

将其从数据库中删除后

然后打印已删除的消息