Create folder and ID simultaneously using the same id number

2

I need to create a folder with the same ID number as the user inserts a new article.

<?php
include './includes/config.php';
setMenu("Notícias");
include './includes/cabecalho.php';

checkLogin();


$erro="";

if ($_POST['salvar']) // noticia clicou no botao salvar
{
    $titulo = $_POST['titulo'];
    $conteudo = $_POST['conteudo'];
    $categoria = $_POST['categoria'];
    $imagem = $_POST['imagem'];
    $data = $_POST['data'];
    $autor = $_POST['autor'];
    $destacar = $_POST['destacar'];
    $status = $_POST['status'];


    $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,categoria,imagem,conteudo,data,autor,destacar,status) VALUES (:titulo,:categoria,:imagem,:conteudo,:data,:autor,:destacar,:status)";
            $stmt = DB::prepare($sqlInsert);
            $stmt->bindParam("titulo", $titulo);
            $stmt->bindParam("categoria", $categoria);
            $stmt->bindParam("imagem", $imagem);
            $stmt->bindParam("conteudo", $conteudo);
            $stmt->bindParam("data", $data);
            $stmt->bindParam("autor", $autor);
            $stmt->bindParam("destacar", $destacar);
            $stmt->bindParam("status", $status);
            $stmt->execute();

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



?>

<div class="col-md-10 col-md-offset-1">
    <form action="noticiasNovo.php"  method="post">

        <div class="panel panel-default">
            <div class="panel-heading">

                <h3 class="panel-title"><strong>Novo Notícia</strong>
                    <a href="noticiasListar.php"  class="pull-right "><span class="glyphicon glyphicon-remove"></span></a>
                </h3></div>
                <div class="panel-body">
                    <?php echo $erro ?>
                    <div class="row">

                        <div class="col-md-6">

                            <div class="form-group">
                                <label for="noticias">titulo:</label>
                                <input class="form-control" id="titulo"  name="titulo"  value="<?php echo $titulo?>" placeholder="Titulo da Noticia" >
                            </div>

                        </div>
                        <div class="col-md-6">

                            <div class="form-group">
                                <label for="noticias">Categoria:</label> <br>
                                <select class="form-control" name="categoria" id="categoria">
                                <option>Selecione a Categoria</option>
                                <?php 
    $sqlcategoria = "SELECT * FROM categoria ORDER BY nome ASC";
    $stmt = DB::prepare($sqlcategoria);
    $stmt->execute();
    $categoria = $stmt->fetchAll();

foreach ($categoria as $u) {
                        echo "<option>{$u->nome}</option>";
                    }

                    ?>
    </select>
                            </div>

                        </div>
                    </div>

                    <div class="col-md-6">
                            <div class="form-group">
                                <label for="noticias">Imagem:</label>
          <input type='file' class="form-control" id="imagem"  name="imagem" placeholder="Selecione a Imagem" >
         </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="noticias">Preview:</label>
                                <img src="" width="100" height="100" id="preview" /> </div>
                        </div>
                        <br><br>
                    <br>

                                <label for="noticias">Conteudo:</label>
                                <textarea name="conteudo" id="conteudo" rows="10" cols="80">
                <?php echo $conteudo?>
            </textarea>



                        <br>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="noticias">Data:</label>
                                <input class="form-control" id="data"  name="data"  value="<?php echo $data?>" placeholder="data da publicação" >
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="noticias">Autor:</label>
                                <select class="form-control" name="autor" id="autor" required>
                                <option>Selecione o Autor</option>
                                <?php 
    $sqlautor = "SELECT * FROM usuarios ORDER BY nome ASC";
    $stmt = DB::prepare($sqlautor);
    $stmt->execute();
    $autor = $stmt->fetchAll();

foreach ($autor as $u) {
                        echo "<option>{$u->nome}</option>";
                    }

                    ?>
    </select>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="noticias">Colocar no Slide? </label> <br>
                                <select class="form-control" name="destacar" id="destacar">
            <option selected value="Desativado">Desativado</option>
            <option value="Destacado">Destacado</option>
          </select>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="noticias">Status</label> <br>
                                <select class="form-control" name="status" id="status">
            <option selected value="Publicado">Publicado</option>
            <option value="Inativo">Inativo</option>
          </select>
                            </div>
                        </div>


                </div>
                <div class="panel-footer">
                    <input type="submit" id="salvar" name="salvar" class="btn btn-default" value="Salvar"></input>

                </div>
            </div>
        </div>
    </form>
</div>

<?php
include './includes/rodape.php';
?>
    
asked by anonymous 02.01.2015 / 17:55

3 answers

3

To create the folder, first check if the insert did not give an error. Make a check in the execute (). Remember that the id is only returned after the insert has been successfully executed and the lastInsertedId () call is in the same session.

if($stmt->execute() === true){
    $id = DB::lastInsertId();
    $nomedapasta = 'pasta_'. $id;
    mkdir = $nomedapasta;

    setMessage("Notícia cadastrado com sucesso.");
    redirect("noticiasListar.php");
}else{
    $erro = setError("Algum erro aconteceu");
}
    
02.01.2015 / 18:03
4

As you have not put other parts of the code, I am considering that you are manipulating a database through the $db object.

$ultimoID = $db->lastInsertId();
if ($ultimoID) {
    mkdir("../imagens/" . $ultimoID); //talvez precise colocar permissões mas resolve a dúvida principal
    setMessage("Notícia cadastrado com sucesso.");
    redirect("noticiasListar.php");
}

This is a simplified form, you can not respond better with so little information.

Pay attention to what I did, I used variable so I did not have to call twice the same thing. And I did not use a variable where I'll only use it once. In the edition of the question gave to see that you did the opposite. It avoided variable where it uses the value twice and created variable for something that only uses once.

I do not know the PDO well, but no examples of documentation show the use of lastInsertID() of the way you are using it. Even though it works, it seems to be the wrong and unsecured way to do it.

    
02.01.2015 / 18:01
2

With the help of @rray and @Maniero gave a better idea about the problem, it was not working after if , just put after execute that worked.

$stmt->execute();

        $ultimoid = DB::lastInsertId();
        $dir = "../imagens/$ultimoid";
        $pasta = @mkdir("$dir", 0777);
    
02.01.2015 / 21:32