File upload, write MYSQL name and path

Asked

Viewed 2,417 times

1

Personal hail!

I have the following doubt, or rather I don’t know how to do it.

I have a resume form that is completed and the user attaches a.pdf file.

Purpose: user fills the form name, email, phone, etc... and attaches the resume in pdf.

This pdf file should be renamed to the completed id-name in the form, and uploaded to the files folder.

And be recorded in mysql database, all form data, and so the file name and its path.

After that has administrative panel that lists the resumes and should show the name and path of the file to download by administrative panel.

I searched the net and I ended up picking up some script parts and I tried to assemble, but it’s not rolling.

I need the help of the people here, I thank who can help.

Explaining what I have of code, and I was able to solve so far, the system at least localhost already sends the file to the specified folder, but not from INSERT in the database of any information.

I have the HTML:

<html>
 <head>
  <title>Upload de arquivos</title>
 </head>
   <body>
      <form class="form-horizontal" method="POST" action="upload.php" enctype="multipart/form-data">

        <label>titulo: </label><br />

           <input type="text" id="titulo" name="titulo" /><br /><br />

              <label>Selecione o arquivo: <br />

                   <input type="file" name="arquivo" id="arquivo" size="45" /></label> <br />

                      <input type="submit" id="btnEnviar" value="Enviar Arquivo" /><br />

                           <input type="hidden" id="arquivo_id" name="arquivo_id" />

     </form>

  </body>

I have the SQL table file and three columns ID - TITLE - FILE

CREATE TABLE `arquivo` (
  `id` int(11) NOT NULL,
  `titulo` varchar(255) NOT NULL,
  `arquivo` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Now PHP:

<?php
$nome_temporario=$_FILES["arquivo"]["tmp_name"];
$nome_real=$_FILES["arquivo"]["name"];
copy($nome_temporario,"imagens/$nome_real");

$servidor = "localhost";
    $usuario = "root";
    $senha = "";
    $dbname = "curriculo";

    //Criar a conexão
    $conn = mysqli_connect($servidor, $usuario, $senha, $dbname);
    if(!$conn){
        die("Falha na conexao: " . mysqli_connect_error());
    }else{
        //echo "Conexao realizada com sucesso";
    }

// Lendo os campos do .html
$arquivo_id = $_POST['arquivo_id'];
$titulo = $_POST['titulo'];
$arquivo = $_FILES['arquivo']["name"];
// ~~~~~~~~~~~~~~~~~~~~~~~~~~

// Codigo de inserção
$sql = "INSERT INTO arquivo (titulo, arquivo_id) VALUES ('$titulo', 'imagens/$arquivo')";

// Converte e Executa a query
$inserir = mysqli_query($conn, $sql);


// Resultado para o .html
if(mysqli_affected_rows($conn) != 0){
                echo "
                    <META HTTP-EQUIV=REFRESH CONTENT = '60;URL=http://localhost/loja/adm/administrativo.php?link=14'>
                    <script type=\"text/javascript\">
                        alert(\"O arquivo foi enviado com sucesso.\");
                    </script>
                ";  
                }else{
                    echo "
                        <META HTTP-EQUIV=REFRESH CONTENT = '60;URL=http://localhost/loja/adm/administrativo.php?link=14'>
                        <script type=\"text/javascript\">
                            alert(\"Arquivo não foi enviado.\");
                        </script>
                    ";  
                }
// Exibe dados sobre o erro:

?>

To well lost in the following. hahahaha

Anyone who wants to help out around here.

I await and thank you

  • escapes the data when going to insert string or any other data in the database: insert x into y(nn,mm) values('{$nn}', '{$mm}') or using double quotes and dots, or instead uses prepared statements that makes the idea clearer.

  • I’m sorry but it wasn’t clear to me.

  • $caminho = "imagens/" . $arquivo; INSERT INTO arquivo (titulo, arquivo_id) VALUES ('{$titulo}', '{$caminho}'). And if you’re testing the code, you should obviously have the bugs enabled, to know specifically what’s going on.

  • Didn’t work... sends the file to folder, but doesn’t save anything to the bank.

  • Which error is returning ? Your field id is auto_increment ?

  • Does not return any error. It sends the file to the images/ - folder but does not insert the data into the database. Wanted to insert the ID and file name in the database.

  • perform this in your table, by phpmyadmin or by console: alter table arquivo modify id int(11) not null auto_increment;

  • Thanks friend! It worked.... Just one more thing, it needed to make the file name be renamed randomly. type: 09938393902.pdf

  • For this, you can simply use uniqid for this task. print uniqid('img_');. But this function does not guarantee that the values will be unique for every time it occurs.

  • Numbers only: $filename = str_pad(mt_rand(0, 9999999), 11, 0); or numbers and letters: $filename = uniqid(md5(Rand())); test in http://kithomepage.com/sos/randNum-ou-Num-Letras.php

  • @Leocaracciolo - Could explain me in my code where to insert, because I tried here and did not roll.

  • This upload is in a server folder?

  • @Leocaracciolo - I got it, I only changed the $nomerquivo = uniqid(md5(Rand()); POR $nome_real = uniqid(md5(Rand());thank you

  • That’s right, $filename was just an example, you had to do what you did now, this variable $real name is not in your code, so I put an example

  • $real name_in the first line of the PHP code - $real name_real = uniqid(md5(Rand())); copy($tempora_name,"files/$real name_real.pdf");

  • But even so, you will know that this variable would be the file name. He

Show 11 more comments

1 answer

1


Start by modifying the table arquivo with the following command:

alter table file Modify id int(11) not null auto_increment;

With this you add the attribute auto_increment at the table.

In a consultation SQL always escape the data you will insert, using double quotes " or braces {}.

$caminho = "imagens/" . $arquivo; 

"INSERT INTO arquivo (titulo, arquivo_id) VALUES ('{$titulo}', '{$caminho}')"
ou
"INSERT INTO arquivo (titulo, arquivo_id) VALUES ('" . $titulo . "', '". $caminho . "')"

To generate unique and random names, you can use the function uniqid:

$caminho = "imagens/" . uniqid('ficheiro_') ; 

There is no guarantee that this function will always return random values, so you can use your own functions for this, see this answer here.

  • Show @Edilson!!! It worked...

  • 1

    @Marcelorossi is still fine.

Browser other questions tagged

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