0

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.)

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Gustavo Mendonça
  • 1,925
  • 3
  • 15
  • 26
  • too much missing code. form, enctype, db code etc. – Funk Forty Niner Nov 06 '15 at 19:20
  • and this is a typo `tpm_name` – Funk Forty Niner Nov 06 '15 at 19:21
  • Check if your really getting any data to $imageData – Olavi Sau Nov 06 '15 at 19:22
  • @Fred-ii- What excactly you need? – Gustavo Mendonça Nov 06 '15 at 19:25
  • @OlaviSau Ok, I will check this now – Gustavo Mendonça Nov 06 '15 at 19:26
  • @GustavoMendonça You need to get the image, save it in some location, then write code to establish db connection with insert query ... ooopsss !! A bit more to go ! Achieve it one by one – Sulthan Allaudeen Nov 06 '15 at 19:28
  • @SulthanAllaudeen I ommited the database code, but I am connecting, executing the sql.. – Gustavo Mendonça Nov 06 '15 at 19:29
  • @GustavoMendonça That's great, and where do you exactly stuck up ? – Sulthan Allaudeen Nov 06 '15 at 19:30
  • http://php.net/manual/en/function.error-reporting.php again `['tpm_name']` is a typo. http://php.net/manual/en/features.file-upload.post-method.php and is most likely the source of the problem. Plus, an enctype is required if using a form. – Funk Forty Niner Nov 06 '15 at 19:31
  • @SulthanAllaudeen The problem is the database says that there is nothing saved in my image column. It says `[BLOB - 0Bytes]` – Gustavo Mendonça Nov 06 '15 at 19:32
  • @Fred-ii- So, what i need to change in my code?? – Gustavo Mendonça Nov 06 '15 at 19:33
  • @GustavoMendonça was there data??? – Olavi Sau Nov 06 '15 at 19:33
  • show your HTML form code (if you are using one, unknown). as I said, `['tpm_name']` is a typo and should read as `['tmp_name']` error reporting would have told you so. also unknown if your query is also failing. – Funk Forty Niner Nov 06 '15 at 19:33
  • @GustavoMendonça Suggestion : Why do you want to store image directly in db, and why not storing it in some location and just storing its path in db ? – Sulthan Allaudeen Nov 06 '15 at 19:34
  • @Fred-ii- I edited and now I placed all the form. – Gustavo Mendonça Nov 06 '15 at 19:37
  • @SulthanAllaudeen Because I want to learn this method of saving images in the database. Just an observation, with I insert a row by myself in the database, the image saves just fine in my row – Gustavo Mendonça Nov 06 '15 at 19:39
  • now you went and edited your question with the POST method without marking it as an edit, in turn my standing to get downvoted for my answer, I've deleted my answer. You'll need to debug your code and read the manuals. – Funk Forty Niner Nov 06 '15 at 19:46
  • @Fred-ii- Sorry for that. I'll try reading the manuals – Gustavo Mendonça Nov 06 '15 at 19:49
  • again, we don't know what your query looks like and whether or not you're escaping the input for it. 9 times out of 10, that is a major reason as to why it failed. your MySQL API is unknown if it's `mysql_` or `mysqli_` or PDO. Either way `mysqli_real_escape_string()` is the `mysqli_` method **required** when uploading using BLOB as a column type. So as of this moment, there is nothing else I can offer that will be of anymore help than I already have "tried" to be. Good luck, I sincerely wish you well. – Funk Forty Niner Nov 06 '15 at 19:52
  • dear Gustavo. These are just reminders nothing mean intended and I just arrived so know nothing. You have been here 18 months (may 10 days in total I don't know i could check). You asked a dozen or two questions. Ok, so Fred answers a question and you change the question out from under him. It takes effort to do those Answers. @Fred-ii- – Drew Nov 06 '15 at 19:55
  • so if you want to **revert** back to a prev version, so the original can be answered (and Fred does a good job at that), then do so. He *presumably* undeletes his Answer. We learn from it. Then create a new question – Drew Nov 06 '15 at 19:56
  • Ok, I don't know what I do now. I think I will post all my code, and if anyone finds a bug I close the question and open another with other question if my problem is not solved. – Gustavo Mendonça Nov 06 '15 at 20:05
  • http://stackoverflow.com/questions/7052655/insert-blobs-in-mysql-databases-with-php --- http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/uploading-files-to-mysql-database.aspx – Funk Forty Niner Nov 06 '15 at 20:05
  • or revert your old question back to the way that it was (or ask Fred to if he will and undelete his Answer in all its glory) **Edit:** Then, if the question posed originally was off base from reality, just create a new question – Drew Nov 06 '15 at 20:06
  • there you have it, `$imagem = $_FILES['imagem'];` needs to be escaped, just as I thought earlier. checking for errors http://php.net/manual/en/mysqli.error.php would have signaled a syntax error. I undeleted my answer to reflect this. – Funk Forty Niner Nov 06 '15 at 20:12
  • @Drew I undeleted it with a few extra goodies, but apparently, it wasn't it. See the comments under my answer. I might leave it, I might delete; time will tell I guess. *Cheers*. Ok, I really have to go. Gf's waiting for me. *ciao for now* – Funk Forty Niner Nov 06 '15 at 20:35
  • 1
    ok @Fred-ii- thx will take a look. As I have not even looked at the versions you guys or any of it – Drew Nov 06 '15 at 20:39

1 Answers1

2

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.

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • I added the method post and wrote right the tmp_name, but didn't worked. – Gustavo Mendonça Nov 06 '15 at 19:44
  • @GustavoMendonça check for errors and visit the PHP.net's manual I left in my answer. "Didn't work" isn't much for me to go on really. – Funk Forty Niner Nov 06 '15 at 19:45
  • @GustavoMendonça I've undeleted my answer and made an edit. Reload it. I have to leave for a while, so I hope this solves it for you. If it doesn't, then I don't know what else to do or say at this point. Do go over it carefully. Good luck. – Funk Forty Niner Nov 06 '15 at 20:24
  • Thanks for the help, but i think i found the problem. I am not sending the data from my form, i am doing it by my script, so i think my javascript is sending nothing! And that's the why I can't see the errors, my javascript block me from seeing what is going on my inserir-artigo.php. The best solution for me is changing the method of saving image on the database, i will save just the path of my image and save the image on the server and it will work fine! – Gustavo Mendonça Nov 06 '15 at 20:31
  • @GustavoMendonça You're welcome. Well, JS isn't my strong point, I'm mostly a serverside kind of guy ;-) well, I'm glad you're on the path to a solution, however you're still going to have to escape the file either way, because it's required when uploading files to a DB using a BLOB type. Otherwise, it will error out. – Funk Forty Niner Nov 06 '15 at 20:33