Error saving to mysql

Asked

Viewed 237 times

-4

Good afternoon to all...

I would like to know the reason for the error in the array below...

This happens when I pass it to record in the database

Array
(
[arquivo] => Array
    (
        [name] => Tabloide Março 2018.pdf
        [type] => application/pdf
        [tmp_name] => /tmp/phpJnYMFn
        [error] => 0
        [size] => 1956251
    )

)

Follow the code

/* Importa o arquivo onde a função de upload está implementada */
$arquivo        = $_FILES["arquivo"]["tmp_name"]; 
$tamanho        = $_FILES["arquivo"]["size"];
$tipo           = $_FILES["arquivo"]["type"];
$nome           = $_FILES["arquivo"]["name"];
$interessado    = $_POST["nome"];
$email          = $_POST["email"];
$cpf            = $_POST["cpf"];
$telefone       = $_POST["telefone"];
$cidade         = $_POST["cidade"];
$interesse      = $_POST["interesse"];
$mensagem       = $_POST["msg"];

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

 $qry = "INSERT INTO trabalhe (id, nome, email, cpf, telefone, cidade, 
 interesse, mensagem, nome_arquivo, arquivo, tipo) VALUES (0, '$interessado','$email','$cpf','$telefone','$cidade','$interesse','$mensagem','$nome','$conteudo','$tipo')";

 mysql_query($qry);

 if(mysql_affected_rows($conn) > 0)
 print "Currículo enviado com sucesso!";
 else
 print "Não foi possível gravar o arquivo na base de dados.";
 }
 else
 print "Não foi possível carregar o arquivo para o servidor.";

it returns me the error: Could not write file to database.

  • This doesn’t seem to have to do with database, are you inserting a pdf into the database? In blob is it? Can’t understand, put your code

  • @Andersonhenrique I really want to record in blob and it returns me this error

  • @Andersoncarloswoss it returns me the error and does not write the file in blob

  • Use the function mysql_error to display some error that helps you in development - leave these messages friendly of "could not do ..." for the production environment. Moreover, there is a mandatory reading for you: Why should we not use mysql type functions_*?

  • I deleted the previous comment, because I think it would lead to some confusion about the technical use, however I still recommend not to upload the data directly in the database. I will formulate a response.

  • Dear @betinhosilva I edited the answer https://answall.com/a/322295/3635 - I had more to say, but I think I would go way beyond asking.

Show 2 more comments

1 answer

2

If you want to get a sense of the error, just do something like:

$qry = "INSERT INTO trabalhe (id, nome, email, cpf, telefone, cidade, 
 interesse, mensagem, nome_arquivo, arquivo, tipo) VALUES (0, '$interessado','$email','$cpf','$telefone','$cidade','$interesse','$mensagem','$nome','$conteudo','$tipo')";

mysql_query($qry) or die( mysql_error() );

It will probably return some syntax error or will state that the id is zero 0 is wrong, yes the id can not be zero, alliis if id for AUTOINCREMENT this field should be omitted, so:

$qry = "INSERT INTO trabalhe (nome, email, cpf, telefone, cidade, 
 interesse, mensagem, nome_arquivo, arquivo, tipo) VALUES ('$interessado','$email','$cpf','$telefone','$cidade','$interesse','$mensagem','$nome','$conteudo','$tipo')";

Another important thing to say, the addslashes is not used to escape in mysql, its purpose is another, Allels none of its variables has escaped:

$interessado    = $_POST["nome"];
$email          = $_POST["email"];
$cpf            = $_POST["cpf"];
$telefone       = $_POST["telefone"];
$cidade         = $_POST["cidade"];
$interesse      = $_POST["interesse"];
$mensagem       = $_POST["msg"];

Any character in this can cause the syntax error in mysql INSERT.

I highly recommend updating your scripts to MYSQLI, ie the bank is still mysql, but the access API is now MYSQLI or PDO, you choose, I believe mysqli will be easier and familiar.

Then following the examples of doc: http://php.net/manual/en/mysqli.affected-rows.php

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
    exit;
}

//Escapa as variaveis conforme as configurações de conexão
$interessado    = mysqli_real_escape_string($link, $_POST["nome"]);
$email          = mysqli_real_escape_string($link, $_POST["email"]);
$cpf            = mysqli_real_escape_string($link, $_POST["cpf"]);
$telefone       = mysqli_real_escape_string($link, $_POST["telefone"]);
$cidade         = mysqli_real_escape_string($link, $_POST["cidade"]);
$interesse      = mysqli_real_escape_string($link, $_POST["interesse"]);
$mensagem       = mysqli_real_escape_string($link, $_POST["msg"]);

//Se o arquivo estiver ok o erro é igual a constante UPLOAD_ERR_OK
if ($_FILES['userfile']['error'] == UPLOAD_ERR_OK) {
    $arquivo        = $_FILES["arquivo"]["tmp_name"]; 
    $tamanho        = $_FILES["arquivo"]["size"];
    $tipo           = $_FILES["arquivo"]["type"];
    $nome           = $_FILES["arquivo"]["name"];

    $fp = fopen($arquivo, "rb");
    $conteudo = fread($fp, $tamanho);
    $conteudo = mysqli_real_escape_string($link, $conteudo);
    fclose($fp); 

    $qry = "INSERT INTO trabalhe (nome, email, cpf, telefone, cidade, 
     interesse, mensagem, nome_arquivo, arquivo, tipo) VALUES ('$interessado','$email','$cpf','$telefone','$cidade','$interesse','$mensagem','$nome','$conteudo','$tipo')";

    //Se funcionar informa quantas linhas foram inseridas (vai retornar "1" sempre/provavelmente)
    if (mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage")) {
        echo 'linhas atualizadas: ', mysqli_affected_rows($link));
    } else {
        //Se falhar informa o erro
        echo 'Erro:', mysqli_error($link)
    }
} else {
     echo 'Erro no upload';
}

Of course I really do not recommend saving the data of an image directly in the database, it would be better to save on disk and put the image path in the database.

I believe this question answers why I do not find a good way to record directly in the bank:

I’m not saying it’s totally wrong, only in most cases it’s not a good way.

If your intention is to block external access to documents you can limit access to folder by using a .htaccess allowing only one php to get the content or if the goal is only to block google and index Bing would just use robots.txt:

Disallow: /imagens/*
  • Is giving this error Got a Packet Bigger than 'max_allowed_packet' bytes

  • @Betinhosilva your Mysql is not set to the amount of data you are sending. But this is another subject.

  • @Betinhosilva pq need to insert image directly inside the bank? I personally find this a not very good way (as I quoted in the last paragraph of the reply), the best would be to save in a folder and just put /imagens/foo.jpg

  • 1
  • @Guilhermenascimento because google was indexing the curricula of the folder... then the client asked for a solution and I ended up finding this :D

  • @Betinhosilva but there is easy to solve, this solution is really not good, with robots.txt you could easily block it.

  • @Guilhermenascimento I will record in folders then... and we will see q dá kkk... but explain to me why recording straight into the bank is unviable?

  • @Betinhosilva has a whole question dedicated to talk about it, if I find you send the link here ;)

  • @Guillhermenascimento waiting for....

  • @Betinhosilva edited the answer, see the end :)

Show 5 more comments

Browser other questions tagged

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