Record multiple images in the database on the same line | Mysql | PHP

Asked

Viewed 324 times

0

I’m not able to record several names of images separated by commas in a column of a row, I’m able to do multiple uploads, but each image name is recorded in a different row of the database. And I wanted it like this: the user uploads 5 photos and all the images inserted in the same column of the same row, each separated by comma in the database:

  --------------------------------------------------------------------------
  ID | img
  --------------------------------------------------------------------------
   1 | image(1).jpg, image(2).jpg, image(3).jpg, image(4).jpg, image(5).jpg
  --------------------------------------------------------------------------

Here is the Form:

<form action="public.php" method="post" enctype="multipart/form-data">
     <input type="file" name="images[]" accept="image/png, image/jpg, image/jpeg" multiple />
     <input type="submit" />
</form>

Follow the PHP code:

$fotoPost = $_FILES['images']; //recebe as imagens passadas pelo input file
$numFoto = count(array_filter($fotoPost['name'])); //conta quantas imagens foram inseridas no input

$folder = "../../arquivs/postagensImg/$dash/"; // pasta do arquivo
$extensao= array('image/jpeg', 'image/png'); // extensões permitidas
$maxSite = 1024 * 1024 * 5; // tamanho máximo da foto

$new_name = substr(sha1(time()).rand().md5(time()), - 40).".".$extensao; novo nome para imagem

for($i=0; $i < $numFoto; $i++){ //estrutura de repetição, só que isso vai adicionando várias linhas
    if(move_uploaded_file($tmp, $folder.$new_name)){
        $sqlInImg = mysqli_query($conn, "INSERT INTO postagem ( img, datePost) VALUES ('$new_name', NOW())");
            if($sqlInImg == true){
                $_SESSION['successPost'] = "Imagem postada com Sucesso";
                header("Location: ../direcao.php");
            }else{
                unlink("../../arquivs/postagensImg/$new_name");
                $_SESSION['errPost'] = "Desculpe, erro ao postar imagem";
                header("Location: ../direcao.php");
            }
        }else{
            $_SESSION['errPost'] = "Error ao adicionar imagem na pasta";
            header("Location: ../direcao.php");
        }
}

I will try to do here with implode(), if I get answer here as I did

  • I’m connected that it seems that can do what I intend with implode(), but someone could show me how more or less?

  • Put in the question the form part and php

  • I already managed to do what I wanted, I will now put the answer I could find, it was easier than I thought, I researched in own kkkkkk curl

2 answers

1

In the loop for you build the variable to be inserted in the bank

$nome = ($_FILES['images']['name'][$i]);

$values .= $nome.","; 

After the loop

//retira a ultima virgula
$values=substr($values, 0, -1);

//Insert declaration

....... VALUES ('$values',NOW()......

0

Fortunately I got the solution to my question, the problem I knew from the beginning that was the repetition of the insertion in the database, but I left because I still did not know what to change to be able to solve, so I was able to solve my problem with implode. There goes the solution I got for those who need to insert several data in the same row and column of the database separated only by ",":

The form remains the same... php is as follows::

$foto = $_FILES['image']; // Capturo as imagens enviadas pelo input[file]
$cont = count(array_filter($foto['name'])); // Faço a filtragem das imagens que foram enviadas como array e conto quantos imagens foram enviadas

for ($i=0; $i < $cont; $i++) { // Aqui é o Macete, faço uma estrutura de repetição 
//<code>for</code>, ele vai comparar a minha variável $i de valor inicial "0", 
//e se for menor do que o $cont, ele vai adicionar até igualar a contagem, 
//ou seja, vai pegar cada nome do array de acordo com a sua posição no array $name[$i] 
//e vai incrementar toda vez que o for é executado no implode, então suas imagens 
///já estarão todas adicionas juntamente em uma única variável separadas por vírgula,
//agora basta apenas registrar no bando de dados


    $name[$i] = $foto['name'];
    $implode = implode(', ', $name[$i]);
}
  • And to separate them to display them, just separate them with the blast(", ")...

  • and to publish in the folder? makes another loop for?

Browser other questions tagged

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