I want to select names which expires in this month and two months ahead.
$t=date('Y');
$q = date('m');
for($e=$q;$e<=($q+2);$e++){
$ren = $t.'-'.$e;
$sql = "select name,renewal_date from hosting_details where renewal_date LIKE '$ren%' ";
}
In this first month display correctly but then onward doesn't give any result. when i echo $ren,for the first month it gives 2016-01 and second month 2016-2.
how can i resolve this
You could simply use sprintf() to format the numbers. For example:
$t=date('Y');
$q = date('m');
for($e=$q;$e<=($q+2);$e++){
$ren = $t.'-'. sprintf("%'.02d", $e);
var_dump($ren);
}
More info on sprintf() can be found in the docs.
However since you're working with dates, why not use a \DateTime object and have it do the work for you? This means you don't have to do any date overflow logic etc - PHP does all the complex work for you! :) e.g.
$begin = new DateTime( '2016-01-11' );
$numMonths = 2;
for($i=0; $i<$numMonths; $i++)
{
// e.g. increment the month and format the date.
var_dump($begin->modify( '+1 month' )->format("Y-m-d"));
// of course modify the format to "Y-m" for your code:
// $ren = $begin->modify( '+1 month')->format("Y-m");
}
For more reading you can checkout \DateTime and \DatePeriod in the PHP docs.
Here's a working example comparing the two approaches.
Using sprintf() can solve your problem:
$t=date('Y');
$q = date('m');
for($e=$q;$e<=($q+2);$e++){
$ren = sprintf('%d-%02d', $t,$e);
$sql = "select name,renewal_date from hosting_details where renewal_date LIKE '$ren%' ";
echo $sql . "\n";
}
Output:
select name,renewal_date from hosting_details where renewal_date LIKE '2016-01%'
select name,renewal_date from hosting_details where renewal_date LIKE '2016-02%'
select name,renewal_date from hosting_details where renewal_date LIKE '2016-03%'
Related
I need to extract only the day number of a user's registration date.
And extract only the day number of the current date.
Simply in an if loop, say if the day number the user registered is equal to the day number of the current date, do this, or do that.
Code:
$manager = "Manager";
$managerPRO = "ManagerPRO";
$q = $connessione->prepare("
SELECT * FROM collaboratori
WHERE cat_professionisti = ?
OR cat_professionisti = ?
");
$q->bind_param('ss', $manager,$managerPRO);
$q->execute();
$r = $q->get_result();
while($rr = mysqli_fetch_assoc($r)){
/*REGISTRATION DATE*/
$registrazione = $rr['data_registrazione'];
$timestamp = strtotime($registrazione);
echo date("d", $timestamp) .'=' ;
/*CURRENT DATE*/
$data_corrente = date('Y-m-d');
$timestamp_uno = strtotime($data_corrente);
echo date("d", $timestamp_uno);
/*CONTROL*/
if ($timestamp == $timestamp_uno){
echo "yes".'<br>';
}else{
echo "no".'<br>';
}
}
Result:
18=18no
17=18no
16=18no
16=18no
Why in the first case if 18 = 18 gives me false?
However, if I change the date of the user's registration and therefore the first 18, from 2020/11/18 to 2020/12/18, then the current month gives me yes!
I need that regardless of the month, just by checking the day if it is the same, tell me yes, where am I wrong?
You are comparing timestamps, which are measured in seconds. What you are doing is effectively comparing two different points in time, not the days of the month.
You really should be using DateTime. If you want to compare only the day part then you can do something like this.
$dt1 = new DateTime($registrazione);
$dt2 = new DateTime(); // defaults to now
if($dt1->format('d') === $dt2->format('d')) {
echo "Yes, it's the same day of the month";
} else {
echo 'no!';
}
My database has y m d fields with no leading zeros in the month and day. I am trying to compare a records y-m-d against today's date. Greater than or equal show a greenlight image else red light. It's not working! HELP!
$q = "SELECT * FROM pec_mbbtmssgs WHERE activity='bike' AND CONCAT(`y`,'-','m','-','d') >= date('Y-n-j')";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$activity = $row['activity'];
if($activity == "bike") {
$image = "greenlight25";
}
else {
$image = "redlight25";
}
echo '<img src=http://img/' . $image . '.gif />';
?>
Your usage of CONCAT() is a bit off, as database-columns should either be wrapped in backticks or nothing at all, and strings/separators in singlequotes '.
You can also just do DATE(NOW()) to get the current date, and compare against this. Then you use the DATE() with the result of your CONCAT(), so it becomes like this
SELECT *
FROM pec_mbbtmssgs
WHERE activity='bike'
AND DATE(CONCAT(y, '-', m, '-', d)) >= DATE(NOW())
The simpler approach would be to just store your date in a DATE type column, instead of 3 separate ones. You can always extract the specific information you want (e.g. you can extract the month, even if your value is 2016-11-30).
$q = "SELECT * FROM pec_mbbtmssgs WHERE activity='bike' AND unix_timestamp(CONCAT(`y`,'-',`m`,'-',`d`)) >= unix_timestamp(CURDATE())";
I am building a php application using pgsql as its back end.
I would like to increment the date by some amount of date shich should be loaded from my database which have given value as available=1,3,5(implying monday,wednesday,friday of a week).I would like to increment these available values to current date. I am using N format in date() function to represent the values of days in a week as 1 to 7 which is stored in available field in the database
If current date =22-07-2013 which is monday,then i have to increment this to wednesday(available=3) and then to friday(available=5) And then to monday of the next week.
And so on..
but i cant do that..
i am in need of such a code where the value of available may change according to the tuples in that tuple.So i would like to increment the current date based on the value of available.
So please help me to achieve it.
The code I used is attached herewith.Please have a look at it.
<?php
$sq = "SELECT * FROM $db->db_schema.dept where active='Y' and dept_id=$dept_id";
$result = $db->query($sq);
$ftime=$result[0]['f_time'];
$ttime=$result[0]['t_time'];
$a=date('Y-m-d').$ftime;
$b=date('Y-m-d').$ttime;
$to_time = strtotime("$b");
$from_time = strtotime("$a");
$minutes= round(abs($to_time - $from_time) / 60,2). " minute";
$days=array();
$days= explode("," , $result[0]['available']);
$result[0]['available'];
$intl=$result[0]['slot_interval'];
$slots=$minutes/$intl;
$dt1 =date("m/d/Y $ftime ");
$s_mnts=explode(":",$ftime);
$m= date('N');
-- $dt=array();
$a=$dt1;
$l=0;
for($n=1;$n<=3;$n++)
{
for($k=$m;$k<=7;$k++)
{ $l=$l+1;
if(in_array($m,$days))
{
echo "dasdsa";
echo date("Y-m-d H:i:s", strtotime("$a +$l days"));
echo"<br>";
}
$m=$m+1;
if($m==7){$m=1;}
}
}
?>
where
dept_id -> primary key of the table dept
$db->query($sq); -> query is used to fetch the given values and is defined in another file named database.php in the program folder.
f_time and t_time -> fields in the table dept which describes the from_time and to_time.f_time is the time from which we have to start increment and t_time is the time to end this increment.
Please inform me whether there is any improvement in the code I have given. .
What you could do is something like this:
You say how many days you want to increment. And give an array of availables.
<?php
$inicialDate = time(); //Timestamp of the date that you are based on
$tmpDate = $inicialDate; //Copy values for tmp var
$increment = 5; //Increment five days
$available = [1,3,5]; //Days available
/*Ok, now the logic*/
while($increment > 0){
$tmpDate = strtotime("+1 day", $tmpDate); //Increase tmpdate by one day
if(in_array(date("N",$tmpDate), $available){ //If this day is one of the availables
$increment--;
}
}
$finalDate = date("m/d/Y",$tmpDate);
?>
This logic should work, although I don't know how to reproduce it via a SQL Procedure.
From what I can tell, you are after something like
UPDATE sometable
SET some_date_column = some_date_column + ('1 day'::INTERVAL * some_integer_value);
I wish to print the totals of a column in my database for each month in the last year. The code I have so far to do this is:
$month = date("n");
$year = date("Y");
$loop = 12;
while($loop>1) {
$first = mktime(0,0,0,$month,1,$year);
$last = mktime(23,59,00,$month+1,0,$year);
$spendingData = mysql_query("SELECT * FROM spending WHERE date BETWEEN $first AND $last") or die(mysql_error());
$totalMonth = 0;
while($spending = mysql_fetch_array($spendingData))
{
$totalMonth = $totalMonth + $spending['amount'];
}
print "£".$totalMonth;
$loop = $loop-1;
print "<br>";
}
My quesiton is how, in the loop, do I adjust the times for each month? I thought about just taking a months worth of seconds away from the timestamps, but as I don't know how many days are in each month I don't think this will work. I also don't think I can just keep taking 1 away from the month figure as this will not account for years. I also don't want to hard code the figures in, as they will change with each new month.
How can I achieve this?
Thank you
You could do this rather trivially in MySQL:
SELECT MONTH(date) AS month, SUM(amount) AS amount
FROM yourtable
WHERE YEAR(date) = $year
GROUP BY MONTH(date)
without ever having to involve PHP for the date manipulation stuff.
I use PHP to perform SQL to pull out some data from my database between a date range. The dates are stored as date in the relation:
$from = "2011-08-11";
$to = "2011 - 08- 25";
$query = mysql_query("SELECT date FROM `entries` WHERE date BETWEEN '$from' AND '$to' ORDER BY date ASC");
I would like to find the earliest date pulled from the relation.
If the query is successful, I store the 'date' attribute in a php array called $dates. I thought I could iterate over this $dates and compare the $date values after converting them into dates.
if($query){
$dates = array();
while($row = mysql_fetch_array($query)){
$dates[] = $row['date'];
}
$min = strftime("%Y-%m-%d", strtotime($dates[0]));
for($i = 1; $i < count($dates); $i++){
if($dates[i] < $min){
$min = $dates[i];
}
}
This does not work however...It prints random values....Perhaps there is a much simpler way to do this and I am overcomplicating matters...
HEEEELLLP!!
If you order your query, then it will be the first (or the last) row in you're query. So you wouldn't need to find it.
Instead of
$min = strftime("%Y-%m-%d", strtotime($dates[0]));
you should use
$min = date("%Y-%m-%d", strtotime($dates[0]));
The simplest way is to use the first date since you know it is already the earliest due to ASC in your SQL statement. After you read the rows into your array, just use the first element.
while($row = mysql_fetch_array($query)){
$dates[] = $row['date'];
}
$earliest_date = $dates[0];
If all you want to do is find just the earliest date, and you don't care about the rest, you could use the aggregate function min() in your query like so:
SELECT MIN(date) AS earliest FROM `entries` WHERE date BETWEEN '$from' AND '$to'
Then just grab the earliest column from the result set in your php code.
Convert the dates to numbers and sort the array?
Take what you have (lines 1-5),
foreach ($dates as $date) {
// convert each date from "YYYY-MM-DD" to "YYYYMMMDD" and turn it into an int
$date = intval(str_replace("-", "", $date));
}
// sort the array from lowest to highest
asort($dates);
// the minimum is the first item in the array
$minint = $date[0];
// convert back into "YYYY-MM-DD" format
$min = substr($minint, 0, 4) . "-" . substr($minint, 4, 6) . "-" . substr($minint, 6);