Do not repeat returned Mysqli data

Asked

Viewed 150 times

0

I have this code that brings me the months registered in the bank. But as it has several lines, I want to return only once each value.

// Fazendo a conexão
    $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 mes FROM programacaoclientes WHERE idCliente = '$idCliente' ");
    $array    = mysqli_fetch_array($query);
    $nums     = mysqli_num_rows($query);

//
    if ( $nums > 0 )
    {   
        // percorrendo
            do
            {   
                // pegando as datas
                    $mes = $array['mes'];

                //
                    echo "<p> <a href='a.php'>$mes</a> </p>";

            }while( $array = mysqli_fetch_array($query) );

    }

Sáida:
  Julho
  Julho
  Julho
  Agosto
  Agosto

I wanted to return only once, without repeating... Which methodology should I use?

1 answer

1


Just put a GROUP BY in hisSELECT:

// Fazendo a conexão
    $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 mes FROM programacaoclientes WHERE idCliente = '$idCliente' GROUP BY mes");
    $array    = mysqli_fetch_array($query);
    $nums     = mysqli_num_rows($query);

//
    if ( $nums > 0 )
    {   
        // percorrendo
            do
            {   
                // pegando as datas
                    $mes = $array['mes'];

                //
                    echo "<p> <a href='a.php'>$mes</a> </p>";

            }while( $array = mysqli_fetch_array($query) );

    }
  • Perfect, Roberto a doubt.. What exactly GROUP BY does?

  • It groups the results by one or more fields, in case we put GROUP BY mes, then mysql will group all results that have the field mes equal.

  • I believe that the DISTINCT in this case would be more appropriate. Example: $query = mysqli_query($conexao, " SELECT DISTINCT mes FROM programacaoclientes WHERE idCliente = '$idCliente' ");

Browser other questions tagged

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