PHP and Mysql: Database does not update

Asked

Viewed 649 times

0

Good afternoon everyone, I’m making a screen for editing personal information. My code to capture the typed data is this:

<?php
require("../config/functions.php");
require("../classes/BDConnection.class.php");
require("../classes/Academico.class.php");
session_start();

$connection = new BDConnection();
$connection->Connect();
$con = $connection->getConnection();

$login = $_SESSION['usuario'];
$password = $_SESSION['senha'];

$email = ClearString($_POST['Email'], $con);

//VERIFICAR SE O NOVO EMAIL JÁ EXISTE NO SISTEMA, EXCETO O DO PRÓPRIO USUÁRIO QUE ESTÁ ALTERANDO
$result = mysqli_query($con, "SELECT email FROM academico WHERE email='".$email."' AND (login <> '".$login."' AND senha <>'".$password."');");
if(mysqli_num_rows($result) >= 1){
    echo "<script>alert('ERRO: E-mail já cadastrado no sistema. Por favor, tente novamente com outro endereço.');
    window.history.back();</script>";
    die();  
}

$user = new Academico();

//INFORMAÇÕES PESSOAIS
$user->setNome(ClearString($_POST['NomeCompleto'], $con));
$user->setDataNascimento( ClearString($_POST['DataNascimento'], $con));
$user->setTelefone( (!empty($_POST['TelFixo'])) ? ClearString($_POST['TelFixo'], $con) : null);
$user->setCelular(ClearString($_POST['TelCelular'], $con));

$user->setEmail($email);

$user->setCidade(ClearString($_POST['CidadeNatal'], $con));
$user->setEndereco(ClearString($_POST['Endereco'], $con));
$user->setBairro(ClearString($_POST['Bairro'], $con));  

$user->setComentario( !empty($_POST['ComentarioAdicional']) ? ClearString($_POST['ComentarioAdicional'], $con) : null);

if($user->AtualizarDados($con)){
    echo "<script>alert('Seus dados foram atualizados');</script>";
}else{
    die('<h3>Erro ao atualizar dados.</h3><br />'.mysqli_error($con));  
}

?>

The data is being captured normally, I tested all variables with echo, but when I call the method Up-to-date(), is returned the success message, however the data is not being updated in BD.

method Updated():

function AtualizarDados($con){
        $result = mysqli_query($con, "UPDATE academico SET nome='".$this->nome."', email='".$this->email."', data_nascimento='".$this->dataNascimento."', endereco='".$this->dataNascimento."', cidade='".$this->cidade."', telefone='".$this->telefone."', celular='".$this->celular."', comentario='".$this->comentario."', bairro='".$this->comentario."' WHERE login='".$this->login."' AND senha='".$this->senha."';")  or die('ERRO: '.mysqli_error($con));

        if(!mysqli_error($con)){
            return true;
        }else{
            return false;
        }
    }

What am I doing wrong?

  • It is totally not recommended to receive the POST values directly on query sql. You need to handle the entries first. For this there is the PDO or in the case Mysqli. Take a look at the link next: Avoiding SQL Inject An easy way to work with the database is to use a library called Redbeans: http://www.redbeanphp.com/ Take a look at the official page. It has super easy examples of how to use.

2 answers

1

function AtualizarDados($con){
$sql = "UPDATE academico SET nome='".$this->nome."', email='".$this->email."', data_nascimento='".$this->dataNascimento."', endereco='".$this->endereco."', cidade='".$this->cidade."', telefone='".$this->telefone."', celular='".$this->celular."', comentario='".$this->comentario."', bairro='".$this->comentario."' WHERE login='".$this->login."' AND senha='".$this->senha."'";

   if ($con->query($sql) === TRUE) {
       echo "Atualização feita com sucesso!";
   } else {
       echo "Error ao atualizar: " . $con->error;
   }
}

Try to do that. (FIXED)

  • continues with the same problem, gives the success message, but when I check the data in BD, they have not changed

  • I think I found! data_nascimento='". $this->dataNascimento." ', address='". $this->dataNascimento." ' <<< Values are repeated

  • Thank you so much for your help!

1


There are two situations if you want to know if you executed the command or if the command affected records. In case you want to know if he changed any record is with the affected_rows.

if($mysqli->affected_rows > 0){
    return true; // registros alterados
}else{
    return false; // não alterado
}
  • run this code, and is returning false. It will be problem is in BD or SQL syntax?

  • @Raphaelhenrique Da um echo in the query you are mounting: echo "UPDATE academico SET nome='".$this->nome."', email='".$this->email."', data_nascimento='".$this->dataNascimento."', endereco='".$this->dataNascimento."', cidade='".$this->cidade."', telefone='".$this->telefone."', celular='".$this->celular."', comentario='".$this->comentario."', bairro='".$this->comentario."' WHERE login='".$this->login."' AND senha='".$this->senha."';"

  • Checks what is appearing and executes the same query directly in the database to see the result.

  • 1

    The login and password values were being passed as empty, I had forgotten to set the object with these attributes... Thank you so much for the help, your tip showed me the error. solved!

Browser other questions tagged

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