Upload Images with PHP + Mysql

Asked

Viewed 53 times

0

I am working on a project that requires the employee’s registration with his image on the form. So far so good, is performing normally the insert, both the data and the image. But when I try update, the linked image (I am working with the bank in varchar 255 and saving the image path in the folder ./fotos) she loses her bond with the ID initially referenced.

I’ve tried countless different code possibilities, but I’m 15 days into it and I can’t get out! Someone can help me?

I only need to accomplish the update of the information and where necessary update image to update it in the employee register.

HTML

    <?php
    session_start();
        if(isset($_SESSION['usuario'])){
            $usuario = $_SESSION['usuario'][0];
            
            
        }else{
            echo "<script> window.location = 'index.php'</script>";
        }
?>
<?php
include_once('conexao.php');
$id = $_GET['id'];
 ?>
 <!--php-->


<!DOCTYPE html>
<html lang="pt-br">

<head>
    <!-- Required meta tags-->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Title Page-->
    <title>1º BPTran</title>

    <!-- Font special for pages-->
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i" rel="stylesheet">

    <!-- Main CSS-->
    <link href="css/main.css" rel="stylesheet" media="all">
</head>

<body>
    <div class="page-wrapper bg-dark p-t-100 p-b-50">
        <div class="wrapper wrapper--w900">
            <div class="card card-6">
                <div class="card-heading">
                    <h2 class="title">Atualizar Cadastro de Efetivo</h2>
                </div>
                <div class="card-body">
                
                
                <?php
                $rs = $conn->prepare("SELECT * FROM tb_efetivo WHERE re=$id");;
        if($rs->execute()){
                if($rs->rowCount() > 0){
                    while($row = $rs->fetch(PDO::FETCH_OBJ)){
        
                    ?>
            
                
                    <form method="POST" action="update_efetivo_img.php">
<!-- DADOS PESSOAIS-->
                        <div class="form-row">
                            <div class=""><h2>Dados Pessoais</h2></div>
                        </div>
                        <div class="form-row">
                            <div class="name">Nome Completo</div>
                            <div class="value">
                                <input class="input--style-6" type="text" name="nome_completo" value="<?php echo $row->NOME_COMPLETO; ?>">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="name">Data de Nascimento</div>
                            <div class="value">
                                <input class="input--style-6" type="text" name="dt_nasc" value="<?php echo $row->DATA_NASCIMENTO; ?>">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="name">CPF</div>
                            <div class="value">
                                <input class="input--style-6" type="text" name="cpf" value="<?php echo $row->CPF; ?>">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="name">RG</div>
                            <div class="value">
                                <input class="input--style-6" type="text" name="rg" value="<?php echo $row->RG; ?>">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="name">CNH</div>
                            <div class="value">
                                <input class="input--style-6" type="text" name="cnh" value="<?php echo $row->CNH; ?>">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="name">Endereço</div>
                            <div class="value">
                                <input class="input--style-6" type="text" name="endereco" value="<?php echo $row->ENDERECO; ?>">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="name">Telefone</div>
                            <div class="value">
                                <input class="input--style-6" type="text" name="telefone" value="<?php echo $row->TELEFONE; ?>">
                            </div>
                        </div>
                        
<!-- DADOS FUNCIONAIS-->                        
                        <div class="form-row">
                            <div class=""><h2>Dados Funcionais</h2></div>
                        </div>
                        <div class="form-row">
                            <div class="name">Posto/Graduação</div>
                            <div class="value">
                                <input class="input--style-6" type="text" name="pg" value="<?php echo $row->P_G; ?>">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="name">RE</div>
                            <div class="value">
                                <input class="input--style-6" type="text" name="re" value="<?php echo $row->RE; ?>">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="name">Nome de Guerra</div>
                            <div class="value">
                                <input class="input--style-6" type="text" name="ng" value="<?php echo $row->QRA; ?>">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="name">Companhia</div>
                            <div class="value">
                                <input class="input--style-6" type="text" name="cia" value="<?php echo $row->CIA; ?>">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="name">Função</div>
                            <div class="value">
                                <input class="input--style-6" type="text" name="funcao" value="<?php echo $row->FUNCAO; ?>">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="name">Email Funcional</div>
                            <div class="value">
                                <div class="input-group">
                                    <input class="input--style-6" type="email" name="email" placeholder="[email protected]" value="<?php echo $row->EMAIL_FUNCIONAL; ?>">
                                </div>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="name">Observações</div>
                            <div class="value">
                                <div class="input-group">
                                    <textarea class="textarea--style-6" name="obs" placeholder="Digite as observações"><?php echo $row->OBS; ?></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="name">Foto de Identificação</div>
                            <div class="value">
                                <div class="input-group js-input-file">                                 
                                    <input type="file" name="foto" value="">
                                    <input class="input--style-6" type="text" name="foto" READONLY="true" value="<?php echo $row->FOTO; ?>">
                                    <img src='./fotos/'<?php echo $row->FOTO; ?>>
                                </div>
                                <div class="label--desc"></div>
                            </div>
                        </div>
        <?php }}} ?>
                        <div class="card-footer" align="center">
                    <input class="btn btn--radius-2 btn--blue-2" type="submit" name="grava" Value="Atualizar"></br></br>
                    <a href="tela_efetivo.php">Cancelar</a>
                </div>
                    </form>
                </div>          
            </div>
        </div>
    </div>

    <!-- Jquery JS-->
    <script src="vendor/jquery/jquery.min.js"></script>


    <!-- Main JS-->
    <script src="js/global.js"></script>

</body>

</html>
<!-- end document-->

PHP:

<?php
session_start();
include_once('conexao.php');
            
$re = $_POST['re'];
$pg = $_POST['pg'];
$qra = $_POST['ng'];
$cia = $_POST['cia'];
$funcao = $_POST['funcao'];
$endereco = $_POST['endereco'];
$telefone = $_POST['telefone'];
$nome_completo = $_POST['nome_completo'];
$email = $_POST['email'];
$dt_nasc = $_POST['dt_nasc'];
$cpf = $_POST['cpf'];
$rg = $_POST['rg'];
$cnh = $_POST['cnh'];
$obs = $_POST['obs'];
$nome_foto =$_POST['foto'];

echo $nome_foto;

//LINK MYSQLI COM BD
    $servidor = "localhost";
    $usuario = "root";
    $senha = "";
    $dbname = "db_efetivo";

// Cria Conexao BD SQL 
$conn = mysqli_connect($servidor, $usuario, $senha, $dbname);
// CHECA A CONEXAO COM O BANCO DE DADOS
if (!$conn) {
  die("Falha de Conexão: " . mysqli_connect_error());
}

$sql = "UPDATE tb_efetivo SET P_G ='$pg', QRA ='$qra', CIA ='$cia', FUNCAO ='$funcao', ENDERECO ='$endereco', TELEFONE ='$telefone', NOME_COMPLETO ='$nome_completo', EMAIL_FUNCIONAL ='$email', DATA_NASCIMENTO ='$dt_nasc', CPF ='$cpf', RG ='$rg', CNH ='$cnh', OBS ='$obs', FOTO ='$nome_foto' WHERE RE='$re'";

if (mysqli_query($conn, $sql)) {
    echo "<script> alert ('Dados atualizados com sucesso!'); </script>";
    echo "<script> window.location.href='index_adm.php'</script>";
} else {
    echo "<script> alert ('Erro ao gravar dados!Entre em contato com o administrador do Sistema!'); </script>";
    echo "<script> window.location.href='index_adm.php'</script>";
}

mysqli_close($conn);
?>
  • You save the image name in the PHOTO column?

  • I saved yes, however when I will call the select through GET, not being able to return the information for the form related to the image

  • My Internet is working well, in my select of all employees back the ID, Name and the image appears in HTML, however when entering Update data, I can’t recover the photo data in the BD and tbm can’t update it

1 answer

0

I’ve been there, I’ll try to explain what the problem is.

What causes this problem is the fact that when you update the data without the image, you are running your code with the image variable $_FILES['foto'] empty, but in your example, above I see you try to send the image name again, not to leave the column empty photo, right?!.

First you need to check if it exists $_FILES['foto']['tmp_name'] being sent, as you can remove the field with the name of the photo.

if(isset($_FILES['foto']['tmp_name']) and $_FILES['foto']['tmp_name'] != ""){
   // Faz o upload da imagem e os dados salva no banco
}else{
   // Salva apenas o dados no banco;
   // Neste caso aqui é opcional passar o nome da foto.
   // Já que ela já vai estar salva na sua tabela então pode remover o campo com o nome
   // E remover essa coluna do seu sql
}
  • I understood the logic of the thing, but I’m not understanding what would be the code to do this update

  • I need that at the time of update, if I choose to replace the photo q ta in the database, it is replaced, or if I choose to update only the data and the image remains the same, happen this, understand?

  • "What causes this problem is the fact that when you update the data without the image, you are running your code with the image variable $_FILES['photo'] empty, but in your example, above I see you try to send the image name again, not to leave the photo column empty, right?!" R: I try to do this so that when replacing the image the same! rsrs

  • Just put the data inside the if up there, in the if I am checking if you were sending the image to replace and in Lse I do not replace the image

  • I’ll take the test and see what happens, Jaja I’ll give you a feedback!!

  • When I make the query, is there any way I can make the input type="file" to be filled with the name of the file q ta saved in the database?

  • This would help the system user to identify whether or not the saved photo is

  • 1

    IT WORKED GNOME!! VLWWWWWW <3

Show 3 more comments

Browser other questions tagged

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