简体   繁体   中英

PHP date between fixed day of every month

I am not a PHP guru but I try and learn as I go. The following also confuses me.

I want to search for results in my SQL between two months from specific day of that month

So lets say today is the 15 August 2013 i want the results to show from the 15 July 2013 to the 15 August 2013 or the current date. But it must start from the 15th of the previous month.

$first = date('Y-m-15');
$last = date('Y-m-15'); //Not sure if i should change this to $last = date('Y-m-t');

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
        $query = "SELECT * FROM pearson_lbs_log WHERE date_time  >=  '" .    
 $first . "' 
 AND date_time  <= '" . $last . "' ORDER BY date_time DESC";
 $result = mysql_query($query);
 echo " ".mysql_num_rows($result)." ";
 ?>

This is for accounting purpose but my accounts run from the 15th of each month to the 15th

I would be nice to see what the account is at when i log on that is why I would like to get the end date as the current date

This code works now:

$first = date('Y-m-15', strtotime("$last -1 month"));
$last = date('Y-m-t'); 

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
        $query = "SELECT * FROM pearson_lbs_log WHERE date_time  >=  '" .    
$first . "' 
AND date_time  <= '" . $last . "' ORDER BY date_time DESC";
$result = mysql_query($query);
echo " ".mysql_num_rows($result)." ";
?>

You can do it php using, try this:

$last=   date('Y-m-15');
$first=  date('Y-m-15', strtotime("$last -1 month")); 

Or in mysql, try this:

where date_time >= date_sub(now() interval 1 month)

Just do:

<?php
$last = date('Y-m-15');
$month-today = date('m'); //get the current month

$lastmonth = $month-today - 1; //subtract one from this month to get last month
if($lastmonth == 00){ //in the case of January and December, December would be 00 (01 - 1 = 00)
$lastmonth = 12;
} 

$first = date('Y')."-".$lastmonth."-15"; //calculate the full variable in Y/lmonth/15 format

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
    $query = "SELECT * FROM pearson_lbs_log WHERE date_time  >=  '" .    
    $first . "' 
    AND date_time  <= '" . $last . "' ORDER BY date_time DESC";
$result = mysql_query($query);
echo " ".mysql_num_rows($result)." ";
?>

The new lines are explained as comments in the code.

I hope this helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM