Why create the folder and not upload the image in sequence?

Asked

Viewed 144 times

0

if ($_POST['salvar']) {
$titulo = $_POST['titulo'];
$conteudo = $_POST['conteudo'];
$imagem = $_POST['imagem'];
 // titulo duplicado
$sql = "SELECT * FROM noticias WHERE (titulo=:titulo)";
$stmt = DB::prepare($sql);
$stmt->bindParam("titulo", $titulo);
$stmt->execute();
$noticias = $stmt->fetch();

if ($noticias)
    $erro = setError("Esse titulo da noticia ja existe !!! Altere o titulo");
else {
     $sqlInsert = "INSERT INTO noticias (titulo,conteudo) VALUES (:titulo,:conteudo)";
    $stmt = DB::prepare($sqlInsert);
    $stmt->bindParam("titulo", $titulo);
    $stmt->bindParam("conteudo", $conteudo);
    $stmt->execute();

    $ultimoid = DB::lastInsertId();
    $dir = "../imagens/$ultimoid";
    @mkdir("$dir", 0777);
    $uploaddir = "$dir/";

   **// a parte de upload da imagem nao funciona  ** 

    @move_uploaded_file($_FILES['imagem']['tmp_name'], $uploaddir . $_FILES['imagem']['name'])) {
    $imagem = $_FILES['foto']['name'];


   **// a parte de upload da imagem nao funciona**

    $sqlInsert = "UPDATE noticias SET imagem=:imagem WHERE idnoticia=$ultimoid";
    $stmt = DB::prepare($sqlInsert);
    $stmt->bindParam("imagem", $imagem);
    $stmt->execute();
}

if (DB::lastInsertId()) {
    setMessage("Notícia cadastrado com sucesso. ");
    redirect("noticiasListar.php");
} else {
    $erro = setError("Algum erro aconteceu");
}

}

just remembering that I have already researched and tried other alternatives and nothing of the image go to the blessed folder

  • I cannot understand the question, please read: How to create a Minimum, Complete and Verifiable example

  • Where is the image upload code? I only see the move_uploaded but this is already the end of the process. Where the variable came from $imagem?

  • Descupem I cut trying to do what Guilherme paid attention to. however it does have the post $image = $_POST['image'];

  • @Arsomnolasco Cara isolate the code, formulate the question, the reading becomes very difficult the way it is. Legible minimum: Use consistent names and indentation, and if necessary include comments to explain parts of the code. Virtually all code editors have a self-training command - find and use! mcve

  • 1

    @Arsomnolasco It gets a little difficult for us to detect any error when you yourself may have missed several using the Suppressor @, remove them and see what errors the code presents. Also check if $FILES['imagem']['error'] is different from 0, see here, put a if in the move_uploaded also to check if it is not returning false.

  • then Cahe was trying to Aki the following : if(move_uploaded_file($_FILES['image']['error']==0)) {
 $sqlInsert = "UPDATE noticias SET imagem=:imagem WHERE idnoticia=$ultimoid";
 $stmt = DB::prepare($sqlInsert);
 $stmt->bindParam("imagem", $imagem);
 $stmt->execute();
 }else{ $erroupload = "moveupload or update error"; } however did not return anything, did the insert in the bd and created the folder

  • @Arsomnolasco do according to the examples I posted.

Show 2 more comments

1 answer

2

Your indentation and markup are bad (sorry for the sincerity) if failures do not happen is by sheer luck.

Returning to the subject, there are the following problems with your code:

  1. @ to omit errors is terrible, do not omit errors when in development environment.
  2. Do error handling with if and else
  3. Close the IFs in the same pattern, do not use if (...) echo 1; in one place and another if (...) { ... }
  4. The indentation helps to yourself understand the code and avoid errors.
  5. In production environments to omit errors use error_reporting(0);
  6. There is a { at the end of @move_uploaded_file($_FILES['imagem']['tmp_name'], $uploaddir . $_FILES['imagem']['name'])) { that has no logic (I will assume that was a typo in the question)

Like I said your code doesn’t have ERROR HANDLING, this is simple to do, just create else for all that is possible.

For example mkdir and move_uploaded_file return boolean that is to say TRUE or FALSE, use this to your advantage.

Example:

error_reporting(E_ALL|E_STRICT);//Apenas para ambiente de desenvolvimento, em ambiente de produção comente está linha
//error_reporting(0);//Em ambiente de produção remova o comentário do inicio desta linha

...

$dir = "../imagens/$ultimoid";
if (mkdir($dir, 0777) === FALSE) {
    echo 'Erro ao criar a pasta: ', $dir, '<br>';
    exit;// é apenas um exemplo
} else {

    $uploaddir = $dir . '/';

    if(FALSE === move_uploaded_file($_FILES['imagem']['tmp_name'], $uploaddir . $_FILES['imagem']['name'])) {
        echo 'Ao subir o arquivo para: ', $uploaddir , $_FILES['imagem']['name'], '<br>';
        exit;// é apenas um exemplo
    } else {
        $imagem = $_FILES['foto']['name'];
    }
...

Note that it is HIGHLY recommendable that you use rollback last INSERT (if you are using innoDB) to prevent that there are multiple records if data.

If you’re not using innoDB (or any other engine compatible with rollback) you will have to use DELETE error occurs during upload.

Example of rollback (only works on Innodb or engines that support rollback):

Myisam does not support rollback

Detail, within your class you should add something like $mysqli->autocommit(FALSE);, this will stop the auto-commit.

The code should look something like:

$ok = FALSE;

$sqlInsert = "INSERT INTO noticias (titulo,conteudo) VALUES (:titulo,:conteudo)";
$stmt = DB::prepare($sqlInsert);
$stmt->bindParam("titulo", $titulo);
$stmt->bindParam("conteudo", $conteudo);
$stmt->execute();

$ultimoid = DB::lastInsertId();

$dir = "../imagens/$ultimoid";
if (mkdir($dir, 0777) === FALSE) {
    echo 'Erro ao criar a pasta: ', $dir, '<br>';
    exit;//Recomendável que você use rollback neste ponto
} else {

    $uploaddir = $dir . '/';

    if(FALSE === move_uploaded_file($_FILES['imagem']['tmp_name'], $uploaddir . $_FILES['imagem']['name'])) {
        echo 'Ao subir o arquivo para: ', $uploaddir , $_FILES['imagem']['name'], '<br>';
        exit;//Recomendável que você use rollback neste ponto
    } else {
        $imagem = $_FILES['foto']['name'];
    }
...
//Após testar todas Ifs incluindo das queries executadas, você deve setar TRUE
$ok = TRUE;
...
//Isto deve ficar no final do código
if ($ok === TRUE) {
    $mysqli->commit();//Se TRUE então "commita" os dados no DB
} else {
    $mysqli->rollback();//Desfaz mudanças
}

You should also create Ifs for each $stmt->execute

Browser other questions tagged

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