Bad practice in PHP code

Asked

Viewed 166 times

-1

I have some functions(down below) of a system of service evaluations. But when I run them in my index.php the server takes too long to run them, the page takes almost 30s to return the data. Something is wrong:

index php.

<!-- avaliações -->
<?php
echo "Atendimento <br />";
echo $winfood->getPorcentNotas("atendimento")."<br /><br />";

echo "Comercial <br />";
echo $winfood->getPorcentNotas("comercial")."<br /><br />";

echo "Suporte: <br />";
echo $winfood->getPorcentNotas("suporte")."<br /><br />"; 

echo "Instalacao: <br />";
echo $winfood->getPorcentNotas("instalacao")."<br /><br />";
?>
<!--// avaliações -->

php class.

<?php
// função 
public function getPorcentNotas($setor)
{
// conexão com banco de dados
  $conexao = mysqli_connect($this->dbservidor,$this->dbusuario,$this->dbsenha) or die(mysqli_connect_error($conexao));
  $select  = mysqli_select_db($conexao,$this->dbnome) or die (mysqli_connect_error($select));

  // for
  $count = 5;
  $i     = 0;

  do
  {
    // busca os dados
    $query   = mysqli_query($conexao, "SELECT COUNT(nota) AS total FROM avaliacoes WHERE setor_area = '$setor' AND nota = '$i'");
    $retorno = mysqli_fetch_assoc($query);
    $total   = $retorno['total'];
    $i++; // incrementa
  }while($i < $count);

  // contar as notas
  $_1      = $this->getCount_Notas_ByNota($setor,"1");
  $_2      = $this->getCount_Notas_ByNota($setor,"2");
  $_3      = $this->getCount_Notas_ByNota($setor,"3");
  $_4      = $this->getCount_Notas_ByNota($setor,"4");
  $_5      = $this->getCount_Notas_ByNota($setor,"5");

  // 
  echo "Horrivel: $_1 pessoa(s)<br />";
  echo "Ruim: $_2 pessoa(s)<br />";
  echo "Razoavel $_3 pessoa(s)<br />";
  echo "Muito bom $_4 pessoa(s)<br />";
  echo "Excelente: $_5 pessoa(s)<br />";

}

// 
public function getCount_Notas_ByNota($setor,$nota)
{
  // conexão com banco de dados
  $conexao = mysqli_connect($this->dbservidor,$this->dbusuario,$this->dbsenha) or die(mysqli_connect_error($conexao));
  $select  = mysqli_select_db($conexao,$this->dbnome) or die (mysqli_connect_error($select));
  $query   = mysqli_query($conexao, "SELECT COUNT(nota) AS total FROM avaliacoes WHERE setor_area = '$setor' AND nota = '$nota'");
  $retorno = mysqli_fetch_assoc($query);
  $total   = $retorno['total'];
  return $total;
}

?>
  • Server local or remoto ?

  • the server is local. Easyphp

  • 1

    This can have several factors, overloaded operating system, etc., etc. Take a test remoto to know if it really is the code.

  • Try to run SELECT in the database only once and optimize your loop. It is possible that you can get the same results with the following SQL SELECT nota, COUNT(nota) AS total FROM avaliacoes WHERE setor_area = '$setor' GROUP BY nota

2 answers

4

Wow, of course it’s taking that long Then you have the following function:

public function getCount_Notas_ByNota($setor,$nota)
{
    // conexão com banco de dados
        $conexao = mysqli_connect($this->dbservidor,$this->dbusuario,$this->dbsenha) or die(mysqli_connect_error($conexao));
        $select  = mysqli_select_db($conexao,$this->dbnome) or die (mysqli_connect_error($select));
        $query   = mysqli_query($conexao, "SELECT COUNT(nota) AS total FROM avaliacoes WHERE setor_area = '$setor' AND nota = '$nota'");
        $retorno = mysqli_fetch_assoc($query);
        $total   = $retorno['total'];
        return $total;
}

And you’re executing it 4 vezes consecutivas, but this nay is the worst!

The worst is that these make connection to the database every time you perform the function getPorcentNotas what is the cause of this delay:

// conexão com banco de dados
  $conexao = mysqli_connect($this->dbservidor,$this->dbusuario,$this->dbsenha) or die(mysqli_connect_error($conexao));
  $select  = mysqli_select_db($conexao,$this->dbnome) or die (mysqli_connect_error($select));

Remove these lines from inside the function and put the part in a file(Connection.php) and include it on the page where you need the connection to the example database:

include('connection.php');
/* Resto do código */

In order to access the variable contained in the file you have to say that the variable $conexao is global in this way:

function funcao(){   
         global $conexao;
    [ echo $conexao; ]

Or if you prefer You can use dependency injection but it’s already PHP-OO (Object-oriented) Learn more here at this link.

I also saw that you are consulting within a loop which is not good for the server:

 do
  {
    // busca os dados
    $query   = mysqli_query($conexao, "SELECT COUNT(nota) AS total FROM avaliacoes WHERE setor_area = '$setor' AND nota = '$i'");
    $retorno = mysqli_fetch_assoc($query);
    $total   = $retorno['total'];
    $i++; // incrementa
  }while($i < $count);

This is perfect for the server to fall, imagine yours script online with 100 requests at the same time each request this script should make a 20 database requests

In total 20 x 100 = 2000 database requests, with a simple script.

of course there would come a time when the server would go down with so many simultaneous request .

In general you are connecting to the database 2 times, select 2 times the database, making darlings in a loop where the interval is thousandths of seconds and running all this 4 times which is not very healthy.

  • 1

    why I hate php.

  • because php should be more standardized! , which leaves things very disorganized among developers.

  • 1

    and I started with php, so I suffer so much today.

  • @13dev I’m following your advice. I created the file winconnect.php but when I run query sql past variable $connection from the file winconnect.php. I have the answer that the variable is undefined does not exist

  • @Emilysilva edited the answer

  • I started with PHP, there is a big difference to other languages, but I don’t see so bad. In addition, if you do this in C# (without putting the instructions in a using block) your code will be as slow as it is. In these languages people usually use the framework. NET and Entity then don’t do this manual process, if they had to do they would be the same problems. Do not blame yourself or think that a language is bad, we are all here to learn. You will see that there are huge differences in various languages.

  • The specific problem of PHP is being multiparadigma and not forcing a development pattern. On the other hand you can use it as a scripting language to manage a server, make quick scripts if you apply an MVC and have a good logic in project management and structuring, you can do great things without complications. See Mailchimp for example about reporting with PHP.

  • @Renancavalieri Yes the whole reason was what I said a little while ago, php is a little out of line with other languages and has many ways to make connections variable statements and so on (multi-paradigm) which makes it kind of disorganized to work together on a project.. but it’s still good language despite its flaws ! :)

Show 3 more comments

1

We consulted a dev here from my city and gave me the following solution in query:

SELECT COUNT(*), setor_area, nota FROM avaliacoes GROUP BY setor_area, nota ORDER BY setor_area

This dispensed with all the functions I listed in the above question.

Browser other questions tagged

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