Is there any way to reduce if's in my code?

-3
function updateUser($usuario, $senha, $adm){
    //Atualiza informações sobre o usuário
    $sql_query; 
    $q_senha = ""; 
    $q_adm = "";
    $dot = "";
    if(!empty($senha)){
        $q_senha = "senha=md5('$senha')";
    }
    if($adm != NULL){
        $q_adm = "adm='$adm'";
    }
    if($adm != NULL and !empty($senha)){
        $dot = ",";
    }
    $sql_query = "update tb_users set ".$q_senha.$dot." ".$q_adm." where usuario='$usuario';";
    return $this->execute($sql_query);
}

I know it's a simple situation and from what I've read the Strategy is an efficient way for cases with many if's, and that's not my case. But I do believe it has some way of reducing through a good use of SQL. But I did not find anything on the internet about it.

    
asked by anonymous 21.08.2018 / 14:43

1 answer

2

You have how to use ternary operator, follow the example:

function updateUser($usuario, $senha, $adm){
    //Atualiza informações sobre o usuário
    $q_senha = (!empty($senha)) ? "senha=md5('$senha')" : "";
    $q_adm = ($adm != NULL) ? "adm='$adm'" : "";
    $dot = ($adm != NULL and !empty($senha)) ? "," : "";

    $sql_query = "update tb_users set ".$q_senha.$dot." ".$q_adm." where usuario='$usuario';";
    return $this->execute($sql_query);
}

You can read more about the ternary operator here .

    
21.08.2018 / 14:52