0

I'd like to know what is more efficient, make just one query and store the result in an array and then check this array using the function in_array from PHP or make a MySQL query every time I need to check the value?

For example: I created this function to store the query in a array, so this query will be made just one time.

 private function carregaPermissoes(){
        $query = mysql_query("SELECT permissao_nome FROM sisgrupopermissoes WHERE id_grupo = ".$this->getGid().";");
        if (mysql_num_rows($query) > 0){
            $array_permissoes = array();
            while ($row = mysql_fetch_array($query)){
                array_push($array_permissoes, $row["permissao_nome"]);
            }
            return $array_permissoes;
        }
    }

Then every time I need to check it I just use this function:

public function checkPermissao($permissao){
        $this->setPermissao($permissao);
        if (in_array($this->getPermissao(), $this->getGrupoPermissao())){
            return true;
        }else{
            return false;
        }
    }

Is it a good way to do it? Or is better make a query every time I need to check it?

  • 4
    Generally, unless you need up-to-date information, the fewer round trips to the database, the better. Note that you are using an archaic, insecure, and deprecated API. – Strawberry Apr 25 '19 at 16:24
  • Agreed with @Strawberry. If you want to find out for sure in a specific case, write it both ways, and measure the performance. https://stackoverflow.com/a/1202746/350538 – Tin Can Apr 25 '19 at 17:39

2 Answers2

1

SQL queries are slow, typically the most common bottleneck after the network. Your function could be simplified into:

public function checkPermissao($permissao)
{
    // The following line smells...
    $this->setPermissao($permissao);
    return in_array($this->getPermissao(), $this->getGrupoPermissao());
}

If you are afraid of the overhead introduced by in_array (that intrinsically uses a sequential search) you can flip the haystack array and use array_key_exists instead.

ntd
  • 7,372
  • 1
  • 27
  • 44
0

You are storing the permission in an array and checking inside. What if someone/admin change the permission, at this time you have the old permission in your array, as per my understanding this is not a good practice to use array.

You can execute the query like

$query = mysql_query("SELECT permissao_nome FROM sisgrupopermissoes WHERE id_grupo = ".$this->getGid()." AND permissao_nome='".$this->getPermissao()."'"); 

and use mysql_num_rows to check the condition

return mysql_num_rows($query)  
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20