简体   繁体   中英

How to save an image to a MySQL database?

I need to save in my database an image that I am getting by an input, but I don't know how to do it. Every tutorial says to save the path and upload the image to the server, but I don't want that, I want to save the image directly to the database!

My inserir-artigo.php:

<?php


 include_once '../banco/banco.php';

    $titulo = $_POST['titulo'];
    $data = date('Y-m-d');  
    $imagem = $_FILES['imagem'];
    $texto = $_POST['texto'];

    if(empty($titulo) || empty($texto)){
        echo 'empty';
    }
    else if (inserirPublicacao($conexao, $titulo, $data, $imagem, $texto) == 1){
        echo 'success';
    } else {
        echo 'error';
    }

    ?>

My banco.php:

    <?php

$conexao = mysqli_connect('localhost', '', '', '');
$conexao->set_charset("utf8");
session_start();

function listaLogin($conexao, $usuario, $senha) {
    $cont = 0;
    $resultado = mysqli_query($conexao, "SELECT * FROM usuarios WHERE login = '{$usuario}' AND senha = MD5('{$senha}');");
    while ($x = mysqli_fetch_assoc($resultado)) {
        $cont++;
    }
    return $cont;
}

function listaPublicacoes($conexao) {
    $publicacoes = array();
    $resultado = mysqli_query($conexao, "SELECT * FROM publicacoes;");
    while ($publicacao = mysqli_fetch_assoc($resultado)) {
        array_push($publicacoes, $publicacao);
    }
    return $publicacoes;
}

function buscaPublicacao($conexao, $id){
    $query = "SELECT * FROM publicacoes WHERE id={$id};";
    $resultado = mysqli_query($conexao, $query);
    return mysqli_fetch_assoc($resultado);
}

function inserirPublicacao($conexao, $titulo, $data, $imagem, $texto){
    $query = "INSERT INTO publicacoes (titulo, data, imagem, texto) VALUES ('{$titulo}', '{$data}', '{$imagem}', '{$texto}');";
    return mysqli_query($conexao, $query);
}



?>

My HTML:

<?php include_once './template/header.php'; ?>
<script>
    $(document).on('change', '.btn-file :file', function () {
        var file = $('#imagem')[0].files[0]
        if (file) {
            var div = document.getElementById('#imagem-nome');
            $('.imagem-nome').append(file.name);
        }
    });
</script>
<script>
    $(document).ready(function () {
        $("#btn-enviar").click(function () {
            var action = $("#novo-artigo-form").attr("action");
            var form_data = {
                titulo: $("#titulo").val(),
                imagem: $("#imagem").val(),
                texto: $("#texto").val()
            };
            $.ajax({
                type: "POST",
                url: action,
                data: form_data,
                success: function (response) {
                    if (response == 'error') {
                        $("#mensagem-artigo-novo").removeClass("alert-success alert-wraning");
                        $("#mensagem-artigo-novo").addClass("alert alert-danger");
                        $("#mensagem-artigo-novo").html("<p id='login-mensagem-erro'>Houve um erro ao adicionar no banco.</p>");
                    }
                    if (response == 'success') {
                        $("#mensagem-artigo-novo").removeClass("alert-danger alert-warning");
                        $("#mensagem-artigo-novo").addClass("alert alert-success");
                        $("#mensagem-artigo-novo").html("<p id='login-mensagem-sucesso'>Artigo adicionado!.</p>");
                    }
                    if (response == 'empty') {
                        $("#mensagem-artigo-novo").removeClass("alert-success alert-danger");
                        $("#mensagem-artigo-novo").addClass("alert alert-warning");
                        $("#mensagem-artigo-novo").html("<p id='login-mensagem-aviso'>Preencha todos os campos.</p>");
                    }
                }
            });
            return false;
        });
    });
</script>

<div class="container pull-left col-md-4 col-xs-12" style="padding-top: 20px">
    <div class="panel panel-default" >
        <form id="novo-artigo-form" enctype="multipart/form-data" action="../banco/inserir-artigo.php" method="post" role="form">
            <div class="panel-body">
                <div class="panel-header">
                    <h1 class="page-header" style="margin-top: 0px">Adicionar um artigo</h1>
                    <div id="mensagem-artigo-novo">

                    </div>
                </div>
                <div class="form-group">
                    <label for="titulo">Título:</label>
                    <input type="text" class="form-control" name="titulo" id="titulo">
                </div>
                <div class="form-group">
                    <p>
                        <label for="imagem">Imagem:</label>
                    </p>
                    <p class="imagem-nome">
                        <span class="btn btn-default btn-file" id="arquivo">
                            Procurar <input type="file" id="imagem" name="imagem">
                        </span>
                    </p>
                </div>
                <div class="form-group">
                    <label for="texto">Texto:</label>
                    <textarea class="form-control" name="texto" id="texto" style="max-width: 100%; min-height: 300px" required></textarea>
                </div>
            </div>
            <div class="panel-footer">
                <button class="btn btn-primary" id="btn-enviar" type="submit" style="margin-bottom: -10px">Enviar</button>
            </div>
        </form>
    </div>
</div>
<?php include_once './template/footer.php'; ?>

When I run this code, it simply saves nothing in my image column, it says the file has 0 bytes.

(I removed the user and password of my connection string, but it exists in my code.)

Edit: (undeleted)

As per your added db code:

There you have it, $imagem = $_FILES['imagem']; needs to be escaped.

$imagem = $_FILES['imagem'];
$imagem = mysqli_real_escape_string($conexao, $imagem);

Just as I thought earlier. Checking for errors http://php.net/manual/en/mysqli.error.php and applying that to your query, would have signaled a syntax error, since you are attempting to insert into a BLOB type of column.

Sidenote: You're not checking for errors anywhere.

Use mysqli_real_escape_string() against it.

Other references:

NOTA: Also make sure that the filesize doesn't exceed what your system files will allow.

  • 4M is the default size.

Consult the following on Stack:


My original answer before OP added the missing POST method to their form, and not marking it as an additional edit.

File processing require a POST method in <form> and yours doesn't have one.

FYI: Forms default to a GET method if the POST method is omitted; add it.

method="post"

Plus, there is a typo in ['tpm_name'] which should read as ['tmp_name']

Consult the manual on files processing:

Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Displaying errors should only be done in staging, and never production.

which would have signaled notices.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM