Order for quantities of days missing to win

2

I have this script in my code:

$sql = "SELECT * FROM os WHERE status2 <> 'Fechado' ORDER BY XXXXXXX ";
$resultado = mysql_query($sql) or die ("Erro na consulta");
while ($linha = mysql_fetch_assoc($resultado)) {

$vencimento = $linha["vencimento"];

$a = explode("-","$vencimento");
$b = explode("-","$hoje");
$antiga= mktime(0, 0, 0, $b[1], $b[2], $b[0]);
$atual= mktime(0, 0, 0, $a[1], $a[2], $a[0]);
$diferenca= $atual-$antiga;
$dias = floor($diferenca/84600);

echo $dias = (int) $dias; 
}

Where returns how many days left to expire. My question is how to Sort the query in MySQL by record with dates closer to winning.

Example below:

 Sendo Hoje - dia 10/01

 data_entrada | vencimento |      Dias

     01/01    |    05/01   |    - 5 "Dias Atrasado"
     01/01    |    11/01   |      1 "Para Vencer"
     01/01    |    12/01   |      2 "Para Vencer"
     01/01    |    13/01   |      3 "Para Vencer"
     01/01    |    14/01   |      4 "Para Vencer"
    
asked by anonymous 19.01.2015 / 23:53

2 answers

2

The vencimento field is the invoice due date, correct?

So the logic of your code looks like this:

$sql = "
    SELECT *, DATEDIFF(vencimento, CURDATE()) dias_para_vencimento
    FROM os
    WHERE status2 <> 'Fechado'
    AND dias_para_vencimento >= 0
    ORDER BY dias_para_vencimento";
$resultado = mysql_query($sql) or die ("Erro na consulta");
while ($linha = mysql_fetch_assoc($resultado)) {
    $dias = $linha['dias_para_vencimento'];
    echo $dias . '<br>';
}

PS: I just can not remember now whether DATEDIFF(vencimento, CURDATE()) returns a positive value or not. If it is negative, just change the order of the arguments. :)

    
20.01.2015 / 01:00
3

You do not have to sort by the number of days to win, mainly because you do not even filter out what is winning. Just an order by the due date. Due date or number of days to win will produce the same order. You do not give much information but I can infer something for what you used and it would look like this:

SELECT * FROM os WHERE status2 <> 'Fechado' ORDER BY vencimento

The rest of the code should not be affected, although it uses a very strange logic that can be improved or even removed if you prefer to do a query that gives you the results you want. >     

20.01.2015 / 00:18