How to limit log display to 30 days from today's date

6

I'd like to be able to limit the display of news that I've written to my banco de dados to 30 days from today's date, for example:

Show registered news from 03/02/2016 to 02/01/2016 , I tried to use some solutions that I found in search but when applying the attempts no registration is displayed, I tried these two tips:

SELECT * FROM tabela_x WHERE Data BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE();

and also this:

SELECT * FROM tabela_x WHERE data between NOW() and DATE_ADD(NOW(), INTERVAL 1 MONTH)

But as I said, no record is displayed, what I have is this:

$aColumns = array( 'Titulo', 'Tipo', 'Data', 'Hora', 'IdNoticia' );
//$aColumns = array( 'IdNoticia', 'Titulo', 'Tipo', 'DATE_FORMAT(Data,"%d/%m/%Y")', 'Hora' );
//$aColumns = array( 'IdUnicoop', 'Descricao' );

/* Coluna de índice (usada para maior eficiência na cardinalidade da tabela - geralmente a chave primária) */
$sIndexColumn = "IdNoticia";

/* Tabela */
$sTable = "Noticia";

/* Informações de conexão do banco */
$gaSql['user']       = "";
$gaSql['password']   = "";
$gaSql['db']         = "";
$gaSql['server']     = "";

/* 
 * Funções locais
 */
function fatal_error ( $sErrorMessage = '' )
{
    header( $_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error' );
    die( $sErrorMessage );
}

/* 
 * Conexão MySQL
 */
if ( ! $gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password']  ) )
{
    fatal_error( 'Não foi possível abrir conexão com o servidor' );
}

if ( ! mysql_select_db( $gaSql['db'], $gaSql['link'] ) )
{
    fatal_error( 'Não foi possível selecionar o banco de dados ' );
}


/* 
 * Paginação
 */
$sLimit = "";
if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
{
    $sLimit = "LIMIT ".intval( $_GET['iDisplayStart'] ).", ".
        intval( $_GET['iDisplayLength'] );
}


/*
 * Ordenação
 */
$sOrder = "";
if ( isset( $_GET['iSortCol_0'] ) )
{
    $sOrder = "ORDER BY  ";
    for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
    {
        if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
        {
            $sOrder .= "'".$aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."' ".
                ($_GET['sSortDir_'.$i]==='asc' ? 'asc' : 'desc') .", ";
        }
    }

    $sOrder = substr_replace( $sOrder, "", -2 );
    if ( $sOrder == "ORDER BY" )
    {
        $sOrder = "";
    }
}
//$sOrder = "ORDER BY Data DESC, Hora DESC";

/* Busca por termo */
$sWhere = "";
if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" )
{
    $sWhere = "WHERE (";
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
        //Customização para filtrar pela coluna de data de forma correta
        if ($aColumns[$i] == "Data")
        {
            $oldData = mysql_real_escape_string($_GET['sSearch']);
            $novaData = implode(preg_match("~\/~", $oldData) == 0 ? "/" : "-", array_reverse(explode(preg_match("~\/~", $oldData) == 0 ? "-" : "/", $oldData)));
            $sWhere .= "'".$aColumns[$i]."' LIKE '%".$novaData."%' OR ";
        }
        else {
            $sWhere .= "'".$aColumns[$i]."' LIKE '%".mysql_real_escape_string( utf8_decode($_GET['sSearch'] ))."%' OR ";
        }
    }
    $sWhere = substr_replace( $sWhere, "", -3 );
    $sWhere .= ')';
}

/* Filtro individual por coluna */
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
    if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
    {
        if ( $sWhere == "" )
        {
            $sWhere = "WHERE ";
        }
        else
        {
            $sWhere .= " AND ";
        }
        $sWhere .= "'".$aColumns[$i]."' LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
    }
}

/* Customização para este script */
if ( $sWhere == "" )
{
    $sWhere = "WHERE Publicar = 'S' AND Data between NOW() and DATE_ADD(NOW(), INTERVAL 1 MONTH)";
}
else
{
    $sWhere .= " AND Publicar = 'S' AND Data between NOW() and DATE_ADD(NOW(), INTERVAL 1 MONTH)";
}

//debug($sWhere);
//debug($sOrder);

/*
 * SQL query
 * Obtenção de dados para exibição
 */
$sQuery = "
    SELECT SQL_CALC_FOUND_ROWS '".str_replace(" , ", " ", implode("', '", $aColumns))."'
    FROM   $sTable
    $sWhere
    $sOrder
    $sLimit
    ";
$rResult = mysql_query( $sQuery, $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );

/* Quantidade de registros encontrados após a filtragem */
$sQuery = "
    SELECT FOUND_ROWS()
";
$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
$iFilteredTotal = $aResultFilterTotal[0];

/* Totalizador de linhas */
$sQuery = "
    SELECT COUNT('".$sIndexColumn."')
    FROM   $sTable
";
$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
$aResultTotal = mysql_fetch_array($rResultTotal);
$iTotal = $aResultTotal[0];

 /*
 * Saída
 */
$output = array(
    "sEcho" => intval($_GET['sEcho']),
    "iTotalRecords" => $iTotal,
    "iTotalDisplayRecords" => $iFilteredTotal,
    "aaData" => array()
);

while ( $aRow = mysql_fetch_array( $rResult ) )
{
    $row = array();
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
        if ($aColumns[$i] == "Data")
        {
            $novaData = date('d/m/Y', strtotime($aRow[ $aColumns[$i] ]));
            $row[] = $novaData;
        }
        else if ($aColumns[$i] == "Titulo")
        {
            /* Saída especial para a coluna Título devido a acentuação */
             $row[] = utf8_encode($aRow[ $aColumns[$i] ]);
        }
        else if ( $aColumns[$i] != ' ' )
        {
            /* Saída Geral */
            $row[] = $aRow[ $aColumns[$i] ];
        }
    }
    $output['aaData'][] = $row;
}

echo json_encode( $output );
    
asked by adventistapr 03.02.2016 в 13:00

2 answers

6

The solution I would apply is to check if the bank date is greater than or equal to -30 days from today's date.

So:

$data = (new DateTime('-30 days'))->format('Y-m-d H:i:s');

$sql = sprintf('SELECT * FROM tabela WHERE campo_data >= "%s"', $data);

Update

It is good to remember that if we use -30 days , we are making the search is also related to the exact time, because the returned time will be the current time.

If we have a registered request 10:10 and the current time is 10:12 , and the date matches the last possible date for verification, you would have problems.

If this is a problem in your case, you can also "zero" the time of the date we are generating by DateTime (before moving on to your SQL, of course):

  $date = new DateTime('-30 days');

  $date->setTime(0, 0, 0);
    
03.02.2016 / 13:10
4

In% with% a MySQL can do this:

SELECT 
    * 
FROM 
    tabela_x 
WHERE 
    Data 
BETWEEN 
    DATE_ADD(NOW(), INTERVAL -30 DAY) 
AND 
    NOW();
    
03.02.2016 в 13:48