How to change an image in the database by ID?

Asked

Viewed 73 times

-1

Hey, everything cool with you guys? I recently started a form where some information is sent to the database, but when I edit some information it changes everything except the image, before it only erased and left blank, now it does nothing... if someone can give a force I thank from now.

consultation page

<?php

//inicia a conexao com o banco 

include_once("conexao.php"); 

//filtro para pesquisa por palavra chave 

$filtro = isset($_GET['filtro'])?$_GET['filtro']:"";

//consulta slq
$sql = "SELECT * FROM eqp";
$consulta = mysqli_query($conexao,$sql);
$registros = mysqli_num_rows($consulta);

?>

<html lang ="pt-br">         

  <head>                      

    <meta charset="utf-8"> 
    <title>Filtro de Busca </title>
        <link rel="stylesheet" href="../agoravai/edicao/form_consultate.css">


  </head>


      <body>

         <div class="container">

            <nav>

                <ul class="menu">

                   <li></li>
                 <a href="inicio.php"><li>Inicio</li></a>
                    <a href="filtros.php"><li>Filtros:</li></a>
                    <a href="telalog_ed_cons.php"><li>Editar Dados:</li></a>





                </ul>

            </nav>

           <section>


              <h1>Consulta por Formularios Enviados Realizada:</h1>
              <br>
              <hr>





               <?php

               //verifica os itens do banco e os exibe
                print" <h1>$registros Registros encontrados:</h1>";

               while($exebirregistros = mysqli_fetch_array($consulta)){

                    $codigo = $exebirregistros[0];
                  $nome = $exebirregistros[1];
                   $setor =$exebirregistros[2];
                   $equipamento =$exebirregistros[3];
                   $numeroserie =$exebirregistros[4];
                   $numeropatrimonio =$exebirregistros[13];
                   $locais =$exebirregistros[5];
                   $motivo =$exebirregistros[6];
                   $enviando = $exebirregistros[7];
                   $recebendo =$exebirregistros[8];
                   $defeito =$exebirregistros[9];
                   $transporte =$exebirregistros[10];
                   $dataid =$exebirregistros[11];
                   $dataret =$exebirregistros[12];
                    $numeropatrimonio =$exebirregistros[13];
                   $arquivo =$exebirregistros[14];
                   $ordemdeservico =$exebirregistros[15];

//alerme para data de envio e entrega de equipamento

$data_atual = new DateTime(date('Y-m-d'));
$data_expiracao = new DateTime($dataret);

$intervalo_em_dias = $data_atual->diff($data_expiracao);

echo $intervalo_em_dias->format('<h4>%R%a DIAS PARA VENCER O RETORNO</h4>');


           echo (" <table border='2px' cellpacing='15px'>

           <tr>
            <td>Codigo: </td>
        <td>Nome:</td>
            <td>Setor:</td>
            <td>Equipamento:</td>
            <td>Anexo N° ".$codigo.":</td>
            <td>Numero de Serie:</td>
            <td>Numero de Patrimonio:</td>
            <td>Local de Envio:</td>
            <td>Motivo Envio:</td>
            <td>Quem esta Enviando:</td>
            <td>Quem esta Recebendo:</td>
            <td>Defeito:</td>
            <td>Meio de Transporte:</td>
            <td>Data ida:</td>
            <td>Data Retorno:</td>


            </tr> ");      

    echo  ("

<tr>

    <td>" . $codigo . " </td><br>

    <td>" . $nome . " </td>

    <td>" . $setor . " </td>

    <td>" . $equipamento . " </td>

    <td class= ok >" . "<img src='upload/".$arquivo."'width=50px height=50px /></td>

    <td>" . $numeroserie . " </td>

    <td>" . $numeropatrimonio . " </td>

    <td>" . $locais . " </td>

    <td>" . $motivo . " </td>

    <td>" . $enviando . " </td>

    <td>" . $recebendo . " </td>

    <td>" . $defeito . " </td>

    <td>" . $transporte . " </td>

    <td>" . $dataid . " </td>

    <td>" . $dataret . " </td>


    </tr>
    <td> <a href='ed_cons_.php?codigo=" . $codigo . "'>editar</td>



    ")
        ;


               }  



               mysqli_close($conexao);

               ?>

                <br>


           </section>


         </div>



     </body>


</html>

ed_cons_.php

<?php
//inicia a conexao com o banco 

include ("conexao.php"); 
?>
<html lang ="pt-br">      
<html>
  <head>                     
    <meta charset="utf-8"> 
    <title>Formulario</title>
    <link rel="stylesheet" href="../agoravai/css/estilo.css">
  </head>       
            <body>

                    <nav>


                            <ul class="menu">
                            <a href="../agoravai/inicio.php"><li>Inicio</li></a>
                             <a href="../aff/consultaeqp.php"><li>Consulta</a>

                               </ul>

                   </nav>



              </body>




        <?php
 //recebe o codigo da pag de consulta        
$iden = isset($_GET['iden'])?$_GET['iden']:"";      

$iden = $_GET ['codigo'];

// consulta no banco de dados         
$sql = "select * from eqp where codigo = '$iden'"; 
$consulta = mysqli_query($conexao,$sql);
$registros = mysqli_num_rows($consulta);
while($linhas = mysqli_fetch_array($consulta)){

//recebe os dados    

$codigo = $linhas ['codigo'];
$arquivo = $linhas['arquivo'];



            echo ("


            <tr>

              <form method='post' action='salva_ed.php''>
            <td>Codigo:</td><td> <input type='text' name='codigo' value='"  .   $codigo . "'> </td>  

              <td>Arquivo em anexo: <input type='file' class= 'anexo' name='arquivo'> </td>

              <br><br>  

             </tr>

      <br><br>

      <input type='submit' class='bnt salvar' value='Salvar'> 



 ");


        }

        ?>


</html>

salva_ed

<?php
//inicia conexão com o banco 
include ("conexao.php"); 

 // recebe o codigo do registro 

$iden = isset($_POST['iden'])?$_POST['iden']:""; 

// codigo registro 

$iden = $_POST ['codigo']; 

// aqui seria onde ele veifica se existe algo no campo arquivo e o substitui por um valor em branco 
if($arquivo == ""){
    $query =("update eqp set arquivo = '' WHERE codigo='$iden'");
}else{

// aqui seria onde fazia o update da imagem, dando um novo nome e movendo para a pasta de upload 
 if(isset($_FILES['imagem']))
   {
      $sql = mysql_query("SELECT * FROM eqp WHERE codigo = '$id' LIMIT 1");
      $resultado = mysql_fetch_assoc($result);

    date_default_timezone_set("Brazil/East"); //Definindo timezone padrão
    $ext = strtolower(substr($_FILES['imagem']['name'],-4)); //Pegando extensão do arquivo
    $new_name = $resultado['foto']; //Definindo um novo nome para o arquivo
    $dir = 'upload'; //Diretório para uploads

    move_uploaded_file($_FILES['imagem']['tmp_name'], $dir.$new_name); //Fazer upload do arquivo

   }

$imagem = $new_name;

$query = mysql_query("UPDATE eqp set arquivo = '$imagem' WHERE codigo='$id'");

  $result1 = mysqli_query($conexao,$sql,$query);

  // Verifica se o comando foi executado com sucesso
  if(!$result1)
    echo "Registro NÃO alterado.";
  else
    echo "Registro Alterado com sucesso.";
}
?>

I think that problem is on this page where saved, because I saw that I would have to delete the image of the bank first to then upload but so far without success (on the editing page more variables are received however as I am only having trouble editing the image I left only the code and image to be displayed to facilitate understanding )

  • 2

    Hello, welcome! I believe the title of your question does not match what you are asking. because in fact you are not uploading an image in the database(blob) you just save a file name and are having problems with the algorithm. Vc can use the code var_dump($imagem,$_FILES); exit; before the last update to check what is coming out of these variables, it is likely that it is returning an invalid value.

  • hello leonancarvalho, thank you so much for your attention!! Dude, I didn’t quite understand the code you sent me, what would be the function of it? I’m sorry about the haha snafu, but in time we learn.. i added it like you said, but still the same problem is giving this error "Notice: Undefined variable: file in C: xammp htdocs.

  • Quiet @noobphp! var_dump serves for you to debug the output of variables through a dump(screen print) more details here: https://answall.com/questions/172775/dif%C3%A7a-entre-var-dump-e-print-r It is a very useful function for debugging during development. As I imagined the reason you’re not saving is because your variable $arquivo is empty, review the treatment logic because it is incorrect.

1 answer

0


Missing inform in your form the attribute enctype="Multipart/form-data"

ed_cons_.php

<form method='post' enctype="multipart/form-data" action='salva_ed.php''>

When sending files it is necessary to specify this tag in the form.

  • ola vitor, well noticed guy haha had not realized that the function was missing but still giving error, now is appearing the following information : "Notice: Undefined variable: new_name in C: xammp htdocs Agoravai salva_ed.php on line 33 NULL array(1) { ["file"]=> array(5) { ["name"]=> string(10) "images.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(24) "C: xammp tmp php4720.tmp" ["error"]=> int(0) ["size"]=> int(7225) } } " I tried to define it as "$new_name =$_FILES['file']; however still of the error

  • Apparently it is just a notification that the variable has not been initialized. No salva_ed after include put the following line and see if this warning comes out. $new_name = "";

  • First of all thank you for the attention Vitor !! come on, I added it right below include and it’s returning the following message: "string(0) "" array(1) { ["file"]=> array(5) { ["name"]=> string(10) "images.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(24) "C: xammp tmp php4B83.tmp" ["error"]=> int(0) ["size"]=> int(7225) } } "

  • You probably left a var_dump or a print_r in the code, these commands are used to print messages on the screen, in this case seems to be printing the variable $_FILES

  • yes, actually I had a var_dump in my code, just after the variable $image=$new_image; after pulling is returning the following: Notice: Undefined variable: id in C: xammp htdocs Now will salva_ed.php on line 38 Warning: mysqli_query() expects at least 2 Parameters, 1 given in C:\xammp\htdocs\agoravai\salva_ed.php on line 38&#xA;&#xA;Notice: Undefined variable: sql in C:\xammp\htdocs\agoravai\salva_ed.php on line 40&#xA;&#xA;Warning: mysqli_query(): Empty query in C:\xammp\htdocs\agoravai\salva_ed.php on line 40&#xA;Registro NÃO alterado.

Browser other questions tagged

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