Delete image from BD and Folder

Asked

Viewed 514 times

0

I’m trying to create a script that excludes the image of the database and folder, but the problem is that it is only excluding from the BD and not from the folder.

Tabela equipes
id, nome, foto

Here is the PHP I’m using:

$id = $_GET["id"];
if($_SERVER["REQUEST_METHOD"] == "POST"){
    if(isset($_POST["deletar"])){
        $sqlDeletar = $pdo->prepare("DELETE FROM equipes WHERE id = :id");
        $sqlDeletar->bindValue(":id", $id);
        $sqlDeletar->execute();
        $dadosDeletar = $sqlDeletar->fetchObject();
        unlink("../upload/".$dadosDeletar->foto);
        echo "Aqui é o link de redirecionar.";
    }else{
        if(isset($_POST["nao"])){
            echo "Aqui é o link de redirecionar.";
        }
    }
}

And here’s the form:

<form action="" method="post" enctype="multipart/form-data">
    <label>
        <input type="submit" name="deletar" value="Excluir">
        <input type="submit" name="nao" value="Não excluir">
    </label>
</form>
  • 2

    You need to make a select before deleting a record. Because, after it is deleted you no longer have the option "$data->photo"

2 answers

0

Check to see if the file exists.

if (is_file("../upload/".$dadosDeletar->foto)) {/*excluir imagem*/} 

Make sure that $dadosDeletar->foto returns the expected value and that you are passing the correct path to the upload folder.

  • ta dando o msm error, will not be enabled something in php.ini ?

  • Please enter the error in your question.

  • Ta dar esse error: General error in

0

As the friend said there in the comments you need to make a select on the photo before removing from the bank, more or less like this.

$id = $_GET["id"];
if($_SERVER["REQUEST_METHOD"] == "POST"){
    if(isset($_POST["deletar"])){
        
        /* Primeiro você precisa saber o nome do arquivo */
        /* Selecione o mesmo no banco */
        $sqlSelect = $pdo->prepare("SELECT foto FROM equipes WHERE id = :id");
        $sqlSelect->bindValue(":id", $id);
        $sqlSelect->execute();
        $dadosSelect = $sqlSelect->fetchObject();

        /* É legal você verificar se o arquivo está lá na pasta */
        if (is_file("../upload/".$dadosSelect->foto)) {
            /* Remove o arquivo */
            unlink("../upload/".$dadosSelect->foto);
        }

        /* Aqui deleta o banco */
        $sqlDeletar = $pdo->prepare("DELETE FROM equipes WHERE id = :id");
        $sqlDeletar->bindValue(":id", $id);
        $sqlDeletar->execute();

        echo "Aqui é o link de redirecionar.";

    }else{

        if(isset($_POST["nao"])){
            echo "Aqui é o link de redirecionar.";
        }

    }
}

My forte is not PDO, but I think this is the solution you need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.