Update SQL with Template Object

Asked

Viewed 79 times

1

I have a method that receives a model with some fields filled, I want to update only these fields, my current method is 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 model, but when there is no data in any field of the model, it overwrites the value that was null, and that’s the problem, I have to update only the fields passed

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

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;
    }

}   
  • 1

    @Igoroliveira tries to do with the edition I made at the end of the post.

  • does not work the query looks like this: UPDATE tb_students SET name=:, surname=:last name, unidadelocal=:, uniadecurricular=:unidadecurricular, diapreparacao=:, liberadoexercicio=:, token=:, sub=: WHERE email=:email

  • I think it would be interesting then to pass the copied object, and change only the data to update

  • 1

    @Igoroliveira I think so too! We are back to the first stage! rsrsrs

  • 1

    @Igoroliveira erased my edits because they will not help. good luck.

  • 1

    Thanks for trying

Show 1 more comment

Browser other questions tagged

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