How to make a form that accepts photo upload and save to database

Asked

Viewed 6,278 times

3

I created a database called Form and table with the following information

contatos (id int A.I, nome varchar(30), idade int(2), foto(blob)

I made that standard form:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
   <form name="CadastroAlunos" type="text" method="post" enctype="multipart/form-data" action="upload.php">

  Nome: <input type="text" name="NomeAluno"></br>
  Idade: <input type="text" name="IdadeAluno"></br>
  Foto: <input type="file" name="image" /></br>
    <input type="submit" value="Enviar" name="envia" />
  </form>

</body>
</html>

UPLOAD.PHP

<?php
     include_once 'conexao.php';

     $nome = $_POST['NomeAluno'];

     $idade = $_POST['IdadeAluno'];

     $foto = $_FILES['image'];

     move_uploaded_file ( string $foto , string $novoDestino );

     $sql = "INSERT INTO contatos (nome, idade, foto) values ('$nome', '$idade', $novoDestino");
?>

How do I record the photo along with more form information?

  • 1

    Use $_FILES to manipulate the file, $_POST for form information and move_uploaded_file to transfer the file to the server.

  • I understood what you said, only I’m having trouble implementing. I had seen some codes before, only the person uploaded the photo to a folder on the computer. I want it to go to the database. I will edit my question and add the php I made. If you can take a look

  • You need to take the contents of the file with file_get_contents this will return a 'string' then just record in the database. You can do a test and print the return of file_get_contents().

  • 2

    I recommend saving the image in a folder and in your database you record the path to the file, saving the file itself in the database is not one of the best practices because your database may get overloaded and start to slow down.

  • 1
  • @rray I will see to it right now.

  • @Rafaelacioly then, in this regard I do not need to worry so much, because this project is academic, I will upload.

Show 2 more comments

2 answers

3


Use the type BLOB for the column foto which will receive the contents of input type="file".

Your PHP code for insertion into the database would look something like this:

<?php
include_once 'conexao.php';

$nome = $_POST['NomeAluno'];
$idade = $_POST['IdadeAluno'];

$imagem = $_FILES['image']['tmp_name']; 
$tamanho = $_FILES['image']['size']; 
//$tipo = $_FILES['image']['type']; 
//$nomeImagem = $_FILES['image']['name'];

if ( $imagem != "none" ) { 
    $fp = fopen($imagem, "rb"); 
    $conteudo = fread($fp, $tamanho); 
    $conteudo = addslashes($conteudo); 
    fclose($fp); 

    $sql = "INSERT INTO contatos (nome, idade, foto) values ('$nome', '$idade', '$conteudo')";

    mysqli_query($conexao, $sql) or die("Algo deu errado ao inserir o registro. Tente novamente."); 

    echo 'Registro inserido com sucesso!'; 

    //header('Location: index.php'); 

    if(mysqli_affected_rows($conexao) > 0) 
        print "A imagem foi salva na base de dados."; 
    else 
        print "Não foi possível salvar a imagem na base de dados."; 

} else 
    print "Não foi possível carregar a imagem.";
?>
  • I tried to implement this way you sent but error in this part : Parse error: syntax error, unexpected ''.png'' (T_CONSTANT_ENCAPSED_STRING) in C:\wamp\www\up\upload.php on line 11. Because it will be this mistake?

  • I made an edition in the code, I had changed the command $nomeFinal= time()'.jpg'; position. Check if the problem persists, if it still occurs try to upload an image . jpg.

  • I changed and tried to upload an image . jpg but the error persists on this line yet Parse error: syntax error, unexpected ''.jpg'' (T_CONSTANT_ENCAPSED_STRING) in C:\wamp\www\up\upload.php on line 9

  • again changed, the error was on the same line. Missing one '.'

  • Now you’ve moved past that part and into one that seems to be more complex: Warning: fopen(1443794568.jpg): failed to open stream: No such file or directory in C:\wamp\www\up\upload.php on line 15 and also Warning: fread() expects parameter 1 to be resource, boolean given in C:\wamp\www\up\upload.php on line 15

  • tried another approach, redacted the answer.

  • There is a more complete example in the PHP documentation: http://php.net/manual/en/features.file-upload.php

  • I made small editions of what you sent me now and it worked. I appreciate the patience. Thank you very much! : D @feresjorge

  • Edit the post with the code working, it might be for someone else. I’m sorry I haven’t tested the code before, we couldn’t.

Show 4 more comments

2

I think it more advisable to save the image path in the bank, I would do so:

<?php
include_once 'conexao.php';

$nome = $_POST['NomeAluno'];

$idade = $_POST['IdadeAluno'];

$foto = $_FILES['image']['tmp_name'];

$tamanho_permitido = 1024000; //1 MB
$pasta = 'uploads';

if (!empty($foto)){
    $file = getimagesize($foto);

    //TESTA O TAMANHO DO ARQUIVO
    if($_FILES['image']['size'] > $tamanho_permitido){
        echo "erro - arquivo muito grande";
        exit();
    }

    //TESTA A EXTENSÃO DO ARQUIVO
    if(!preg_match('/^image\/(?:gif|jpg|jpeg|png)$/i', $file['mime'])){
        echo "erro - extensão não permitida";
        exit();
    }

    //CAPTURA A EXTENSÃO DO ARQUIVO
    $extensao = str_ireplace("/", "", strchr($file['mime'], "/"));

    //MONTA O CAMINHO DO NOVO DESTINO
    $novoDestino = "{$pasta}/foto_arquivo_".uniqid('', true) . '.' . $extensao;  
    move_uploaded_file ($foto , $novoDestino );

} 


$sql = "INSERT INTO contatos (nome, idade, foto) values ('$nome', '$idade', $novoDestino";

echo $sql;
?>

Browser other questions tagged

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