Insert multiple php mysql records

Asked

Viewed 882 times

0

I am developing a record site and when the user register the vehicle he has the option to insert various images of the vehicle. I have the upload code, but I wanted to know how to insert more than one image in the tabala image field (Example Database: imagem_vehicle : 01.jpg, 02.jpg,...) or I don’t know if it is better to insert multiple lines in a specific table. If anyone can give examples.

if(isset($_POST['upload'])){

    //INFO IMAGEM
    $file       = $_FILES['img'];
    $numFile    = count(array_filter($file['name']));

    //PASTA
    $folder     = 'upload';

    //REQUISITOS
    $permite    = array('image/jpeg', 'image/png');
    $maxSize    = 1024 * 1024 * 10;

    //MENSAGENS
    $msg        = array();
    $errorMsg   = array(
        1 => 'O arquivo enviado excede o limite definido na diretiva upload_max_filesize do php.ini.',
        2 => 'O arquivo excede o limite definido em MAX_FILE_SIZE no formulário HTML.',
        3 => 'O upload do arquivo foi feito parcialmente.',
        4 => 'Nenhum arquivo foi enviado.',
        6 => 'Pasta temporária ausênte.',
        7 => 'Falha em escrever o arquivo em disco.',
        8 => 'Uma extensão do PHP interrompeu o upload do arquivo.'
    );

    if($numFile <= 0)
        echo 'Selecione uma imagem!';
    else{
        for($i = 0; $i < $numFile; $i++){
            $name   = $file['name'][$i];
            $type   = $file['type'][$i];
            $size   = $file['size'][$i];
            $error  = $file['error'][$i];
            $tmp    = $file['tmp_name'][$i];        

            $extensao = @end(explode('.', $name));
            $novoNome = rand().".$extensao";

            if($error != 0)
                $msg[] = "<b>$name : </b>".$errorMsg[$error];
            else if(!in_array($type, $permite))
                $msg[] = "<b>$name : </b> Erro imagem não suportada!";
            else if($size > $maxSize)
                $msg[] = "<b>$name : </b> Imagem ultrapassa limite de 10MB";
            else{

                if(move_uploaded_file($tmp, $folder."/".$novoNome))
                    $msg[] = "<b>$name : </b> Upload realizado com sucesso!";
                else{
                    $msg[] = "<b>$name : </b> Desculpe ocorreu um erro!";
                }

            }

        }


        $insert = "INSERT INTO upload 
                    (imagens)
                    VALUES 
                    ('{$novoNome}')";
        $exe_insert = mysql_query($insert, $con);

    }

}

3 answers

2


The correct thing is to have a table of images, and put a row for each image. In this table you have to have the id referencing the vehicle registration:

Example:

Table of Vehicles:

CREATE TABLE `test`.`veiculos`(
  `id` INT NOT NULL AUTO_INCREMENT,
  `marca` VARCHAR(50) DEFAULT '',
  `modelo` VARCHAR(100) DEFAULT '',
  `ano` YEAR,
  `datacadastro` DATETIME,
  `datamodificacao` DATETIME,
   PRIMARY KEY (`id`)
);

Image Table

CREATE TABLE `test`.`imagens`(
  `id_veiculo` INT DEFAULT 0,
  `imagem` VARCHAR(255) DEFAULT ''
);

Already the INSERT you can do in a single query, for example:

INSERT INTO imagens (id_veiculo, imagem) VALUES
(1, 'imagem1.jpg'),
(1, 'imagem2.jpg'),
(1, 'imagem3.jpg');
  • I thought it was really cool your idea Roberto, but the problem I have is that he is saving in the bank only the name of the last selected image, but in the destination folder he sends all the images. Do you have any idea what it might be?

  • 2

    This happens because your INSERT this outside the FOR, for this reason he saves only the last

  • Great guy, it worked fine thank you very much

0

Or also as friend above said putting:

create table images(
id int unsigned not null auto_increment,
id_veiculos int unsigned default null,
imagem blob not null,
primary key (id),
constraint fk_veiculos_id foreign key (id_veiculos) references veiculos(id)
);

-1

  • This is not his doubt. His doubt is how the image path would be stored in the database.

Browser other questions tagged

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