php – Save the binary content of an image to the database

Question:

How do I get the bytecode of an image at upload time to be able to store it in mysql's blob field without the need to save the image in ftp?

Answer:

If what you want is to simply save an image in BD, here is a suggestion on how to do it:

Listing 1: Database table creation script

CREATE TABLE PESSOA (  
    PES_ID int NOT NULL AUTO_INCREMENT PRIMARY KEY,  
    PES_IMG BLOB  
);

Listing 2: Upload form

<form action="gravar.php" method="POST" enctype="multipart/form-data"> 
    <label for="imagem">Imagem:</label> 
    <input type="file" name="imagem"/> <br/> 
    <input type="submit" value="Enviar"/> 
</form>

Listing 3: Bank image recording script

<?php 
$imagem = $_FILES["imagem"]; 
$host = "localhost"; 
$username = "root"; 
$password = ""; 
$db = "test"; 

$acesso = 'mysql:host=' . $host . ';db=' . $db; 

// Recebeu a imagem
if($imagem != NULL):
    $nomeFinal = time().'.jpg'; 

    // Tenta gravar o arquivo no servidor
    if (move_uploaded_file($imagem['tmp_name'], $nomeFinal)): 

        // Pega a imagem
        $tamanhoImg = filesize($nomeFinal); 
        $mysqlImg = addslashes(fread(fopen($nomeFinal, "r"), $tamanhoImg)); 

        // Conecta-se ao BD e tenta gravar
        try{
            $pdoConecta = new PDO( $acesso, $username, $password ) ;
            $pdoConecta->query("INSERT INTO PESSOA (PES_IMG) VALUES ('$mysqlImg')");
        } catch( PDOException $e ) {
            echo $e->getMessage();
        }

        // Apaga o arquivo
        unlink($nomeFinal); 
    endif;

else:
    echo"Você não realizou o upload de forma satisfatória."; 
endif;
?>

Source : http://www.devmedia.com.br/upload-de-imagens-em-php-e-mysql/10041

Scroll to Top