Create folder and ID simultaneously using the same id number

Asked

Viewed 284 times

3

I need that when the user is entering a new article to be created a folder with the same number as the article ID.

<?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';
?>
  • 1

    in your if(DB::lastInsertId()) you are already getting the registration ID. Just use it: $nomedapasta = DB::lastInsertId();

  • 1

    lastInsertId() returns the id of the inserted record, I don’t understand what the difficulty is.

  • the same difficulty is to insert the post image in this folder that has just been created

  • Any answers solve the problem? Think some can be accepted?

3 answers

4

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

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

I put in the Github for future reference.

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

Pay attention to what I did, I used variable to not have to call twice the same thing. And I did not use variable where I will only use once. When editing the question you can see that you did the opposite. Avoided variable where uses the value twice and and created variable for something that only uses once.

I don’t know the PDO well but no example of documentation shows the use of lastInsertID() the way you are using it. Even if it works, it seems to me to be the wrong and unsafe way to do.

  • the folder is being created but somehow this inserting 2 ids

  • I can’t see why this should happen. Or I don’t understand what you mean by this.

4


To create the folder check first if the Insert did not fail. Do a check on execute(). Remember that the id is only returned after the Insert is 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");
}
  • vlw rray, more like in my case I would insert the post image into this folder, as I might pick up the image after it has already inserted?

  • Make a new query that returns the image or its path by passing the inserted id.

  • has started to duplicate the Inserts , but the folder is created with the number of 2 Insert

  • That code is inside a for?

  • 1

    not this, I will edit the post by putting the whole code

3

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

$stmt->execute();

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

Browser other questions tagged

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