How to order query using PDO?

Asked

Viewed 133 times

1

How can I sort my query from the latest to the oldest date.

This is my Query ?

public function RetornaAtualizacoesFuncionarios($data,$codusuario){ 
    $WHERE = array() ;
    if( !empty( $codusuario    ) ) {$WHERE[] = "codusuario = $codusuario";};
    if( !empty( $data   ) ) {$WHERE[] = "DATE_FORMAT(data,'%Y-%m') = '$data'";};
    $WHERE[] = "tipregistro = 'mysql'";

try {

     $Query = "SELECT 
                    DISTINCT(funcionarios.usuario),
                    date_format(funcionarios.data,'%d/%m/%Y %H:%i:%s') as data ,
                    codigo,
                    nome 
                        FROM funcionarios
                                  "; 

    if( !empty($WHERE) )$Query .= ' WHERE '.implode(' AND  ', $WHERE );

    // echo "<pre>"; print_r($Query);

    include_once $_SESSION['pmodel'].'/mysqlconnection_class.php';
           $p_sql = MysqlConnection::getInstance()->prepare($Query);

            $_retorno = array(); 
            if($p_sql->execute()) {
                while ($_result = $p_sql->fetch(PDO::FETCH_ASSOC))  {
                    $_retorno[] = $_result; 
                }
            }
            return $_retorno;
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }
}

1 answer

1


Just add the clause ORDER BY in its query with the DESC:

$Query = "SELECT 
                DISTINCT(funcionarios.usuario),
                date_format(funcionarios.data,'%d/%m/%Y %H:%i:%s') as data ,
                codigo,
                nome 
                FROM funcionarios";

if( !empty($WHERE) )$Query .= ' WHERE '.implode(' AND  ', $WHERE );

$Query .= " ORDER BY funcionarios.data DESC"; 
  • But this way this error SQLSTATE[42000]: Syntax error or access Violation: 1064 You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near 'WHERE codusuario = 16 AND DATE_FORMAT(date,'%Y-%m') = '2016-10' AND tipregistr'

  • sorry, I didn’t see you insert the WHERE then the ORDER BY has to come last, I’ll edit the answer.

  • 1

    well manage by putting the ORDER BY employees.data DESC at the end of $WHERE

  • That’s right, I edited the answer!

  • Good worked that way too , thank you.

  • Don’t forget to mark the correct answer if you have helped! ;)

Show 1 more comment

Browser other questions tagged

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