SQL Update with Model Object

1

I have a method that receives a template with some fields filled in, I want to update only these fields, my current method looks like this:

    public function atualizar($aluno,$email)
{
    $sql = new Sql();

    if ($aluno->email == null){
        $aluno->email = $email;
    }
    if ($aluno->senha != null){
        $hash = Bcrypt::hash($aluno->senha);
        $aluno->senha = $hash;
    }

    try {
        return $sql->query("UPDATE tb_alunos SET nome= :nome,sobrenome=:sobrenome, email=:email,senha=:senha,unidadelocal=:unidadelocal,unidadecurricular=:unidadecurricular,diapreparacao=:diapreparacao,liberadoexercicio=:liberadoexercicio,token=:token,sub=:sub WHERE email=:email", $aluno);

    } catch (\PDOException $e) {
        echo $e;
        return false;
    }


}

It updates, using the template, but when there is no data in some field of the model, it overwrites the value that was null, and that is the problem, I have to update only the past fields

EDIT

UPDATE tb_alunos SET sobrenome=:sobrenome, unidadecurricular=:unidadecurricular WHERE email=:email

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
    
asked by anonymous 19.02.2018 / 19:03

1 answer

1

You can create the query string according to the values that are sent. For example:

    public function atualizar($aluno,$email)
{
    $sql = new Sql();

    $query = "UPDATE tb_alunos SET "; // string inicial

    if ($aluno->email == null){
        $aluno->email = $email;
        $query .= "email=:email, "; // concatena o email que será alterado
    }
    if ($aluno->senha != null){
        $hash = Bcrypt::hash($aluno->senha);
        $aluno->senha = $hash;
        $query .= "senha=:senha, "; // concatena a senha que será alterada
    }

    // análise dos outros campos

    $query = substr($query , 0, -2); // aqui ele apaga a ultima vírgula e o espaço
    $query .= " WHERE email=:email"; // concatena o final da query

    try {
        return $sql->query($query , $aluno);

    } catch (\PDOException $e) {
        echo $e;
        return false;
    }

}   
    
20.02.2018 / 01:38