strtotime php mysql - php

All I'm trying to do is make the php file accumulate the end date from the sub date. I don't understand why this strtotime function isn't working. My database stores dates as "Y-m-d".
here's the code:
//disguised for security reasons
$db = mysql_connect("*******", "*******","********");
mysql_select_db("*******",$db);
$getad = mysql_query("SELECT id, annual_sub_date FROM members WHERE annual_sub_date!=null", $db);
while ($gad = mysql_fetch_array($getad)) {
$id = $gad['id'];
$asd = $gad['annual_sub_date'];
$aedate_time = strtotime('+1 year', $asd);
$aedate = date("Y-m-d", $aedate_time);
mysql_query("UPDATE members SET annual_end_date='$aedate', annual_active='Y' WHERE id='$id'");
}
---------SOLVED IT---------
I went and played XBox Split/Second for a bit and then realised the issue. My mind went back to PHP/MySQL 101. I coded everything right except the "!=null" part.
//Wrong Way
$getad = mysql_query("SELECT id, annual_sub_date FROM members WHERE annual_sub_date!=null", $db);
//Correct Way
$getad = mysql_query("SELECT id, annual_sub_date FROM members WHERE annual_sub_date IS NOT NULL", $db);
Now everything works :) That's the issues you can expect coding at 5:01am.

The first argument to strtotime is an absolute or relative date as a string, the second argument is an integer timestamp. You're giving it a relative date (string) as the first argument and an absolute date (also string) as the second. You need to convert $asd to a timestamp using strtotime first.
$aedate_time = strtotime('+1 year', strtotime($asd));
BTW, you could do the whole date calculation and updating in SQL with a single query, no need to take the long way around through PHP.

It's because strtotime requires timestamp as second argument and not string date in Y-m-d.
Just try code snippet below to see what I ment.
$gad = array('annual_sub_date' => '2010-11-21');
// wrong
// $asd = $gad['annual_sub_date'];
// good; convert to timestamp
list($year, $month, $day) = explode('-', $gad['annual_sub_date']);
$asd = mktime(0, 0, 0, $month, $day, $year);
$aedate_time = strtotime('+1 year', $asd);
$aedate = date("Y-m-d", $aedate_time);
echo $aedate . "\n";

Related

mysqli prepared statements with between clause

My question is similar to [this][1] but the solution provided there doesn't work for me.
I have a DB and I have one column called birth that contains a date in the format year-day-month 00:00:00. Now I want to extract from the DB all the records which birth is between two dates.
The birth value has been inserted in the DB with this code
$date = $day . "-" . $month. "-" . $year;
$a = strptime($date, '%d-%m-%Y');
$DB_date = date('Y-m-d H:i:s',mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900));
To extract the dates I am using this code:
$stmt = $conn->prepare('SELECT * FROM database WHERE `birth` BETWEEN ? AND ?');
$start_date = '1990-01-01';
$stop_date = '1995-01-01';
$stmt->bind_param('ss',$start_date,$stop_date);
$stmt->execute();
$result = $stmt->get_result();
but it doesn't find anything so $result->num_rows is equal to 0 and it doesn't give any errors so the problem must be in the comparison of the dates.
Birth column format is y-d-m hour min sec. But in your where clause you are ignoring hour minute second factor.
Replace:
$start_date = '1990-01-01';
$stop_date = '1995-01-01';
With this:
$start_date = '1990-01-01 00:00:00';
$stop_date = '1995-01-01 00:00:00';
Kindly try it and let me know if it works
I found the solution
The code in my question works if the data type of the column in the DB is datetime and you also need to make sure that $start_date is older than $stop_date. I still wonder though why it didn't work with the date data type.
I had the same issue. I found another thread with the same problem (not sure how to duplicate this thread) here
However just to sum up,
They managed to get the desired results by bracketing the question marks for the params.
$stmt = $conn->prepare('SELECT * FROM database WHERE `birth` BETWEEN (?) AND (?)');
$start_date = '1990-01-01';
$stop_date = '1995-01-01';
$stmt->bind_param('ss',$start_date,$stop_date);
$stmt->execute();
$result = $stmt->get_result();
Hope this helps.

Creating a Timestamp from a URL string

I have read the manual - but can't seem to find what I need. I don't need the actual date - I need the date I tell it is from the URL
This is what I have currently:
//create search string for posts date check
if($Day <= 9) {//ensure day is dual digit
$fix = 0;
$Day = $fix . $Day;
}
$Day = preg_replace("/00/", "/0/", $Day);
$date = $_GET["Year"];
$date .= "-";
$date .= $_GET["Month"];
$date .= "-";
$date .= $_GET["Day"];
$currently = mktime (0,0,0,$Month,$Day,$Year,0); //create a timestamp from date components in url feed
//create display date from timestamp
$dispdate = date("l, j F Y",$currently);
When I echo $date it reads correctly for the variable string supplied in the URL but $dispdate always returns the current day that it actually is today. I need $currently to be the timestamp of the date in the URL too.
You seem to construct a valid, readable datestring from the GET parameters. Use
$currently = strtotime($date).
It will return a timestamp that you can use to create the $dispdate like you already do with the date function.
Seems like not all the OP's code was posted, so this is based on what is known.
In the line:
mktime (0,0,0,$Month,$Day,$Year,0)
You are using variables that aren't shown to us (so we must assume are not being set to anything). Above this line you are building a "$date" variable with the URL parameters. This is what should be used in your mktime function.
You could use a Datetime object, pass the given parameters and format the output anyway you want.
<?php
//replace with GET params
$year = 2015;
$month = 10;
$day = 01;
$datetime = new Datetime($year.'-'.$month.'-'.$day);
echo $datetime->format('Y-m-d');
?>

Adding current date to DATE table mysql ERROR

I am having some problems getting my date into my SQL table. I do not use datetime, but date.
This is the code I use, and the problem is that my SQL server doesn't recognize $date_add as a date and just puts the default 0000-00-00 in the date section...
if (isset($_POST['postbutton'])){
$articlepost = nl2br($_POST['article'])."<br>";
date_default_timezone_set('Europe/Oslo');
$datepic = date(YYYY-MM-DD);
$pictureurls = $_SESSION['urlpost'];
$thumbnail = 123;
$title = $_POST['title'];
$date_add = $datepic;
$articlepostimg = $articlepost.$pictureurls;
$insertpost = $db->prepare("INSERT INTO posts (title,post,date_add,thumbnail) VALUES (:title,:post,:date_add,:thumbnail)");
$insertpost->execute(array(':title' => $title, ':post' => $articlepostimg, ':date_add' => $date_add, ':thumbnail' => $thumbnail));
unset($_SESSION['urlpost']);
}
Here is what I see in my database after I submit my form:
Try the following:
$datepic = date("Y-m-d");
Here are the docs for date()
As for the question added in your comments, after you retrieve your date you'll need to do something like the following, where $orig_date is assigned the date retrieved from the database. As for converting it to Norwegian, I think you'd have to look into setlocale(), which I think warrants a different question.
$formatted_date = date('j, M Y', strtotime($orig_date));
You need to use either double quote or quotes to make date() function work propely
$datepic = date('YYYY-MM-DD');
This is just to add to already given answers after seeing OP asked for a language conversion in Norwegian, and by no means is it meant to step on anyone's feet, but as a complimentary answer.
You can use the following month conversion code which are in French, but you can easily modify it in Norwegian.
Notice that "Mars" is spelled the same way.
(This taken from my own code library)
<?php
// enter date format 2011-01-31 (Y-m-d)
function date_in_french ($date){
$week_name = array("Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi");
$month_name=array("","Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août",
"Septembre","Octobre","Novembre","Décembre");
$split = preg_split('/-/', $date);
$year = $split[0];
$month = round($split[1]);
$day = round($split[2]);
$week_day = date("w", mktime(12, 0, 0, $month, $day, $year));
return $date_fr = $week_name[$week_day] .' '. $day .' '. $month_name[$month] .' '. $year;
}
$currentDate=date('Y-m-d');
echo "Current Date: ";
echo date('D')." ".date('d')." ".date('M')." ".date('Y');
echo "<br>";
echo "Date in French => ".date_in_french($currentDate);
?>

MYSQL Date range query not working correctly

I have a problem getting certain data from my database by querying a date range. In my database i have a DATE type field within the format YYYY-MM-DD. I want to get all data within a date range of today + 2 weeks (Expiring).
I have wrote:
$format = 'Y-m-j';
$date = date ( $format );
$new = date ( $format, strtotime ( '+14 day' . $date ) );
$start = date("Y-m-d", strtotime($new));
$today = date('Y-m-d');
$q = "SELECT * FROM listing WHERE dd_end BETWEEN '".$today."' AND '".$start."'";
while($row = mysql_fetch_assoc($q)){
$listing_id = $row['listing_id'];
echo "$listing_id";
}
So what I want to achieve is for the query to pull all the rows from now until 5th October. I've echo'd the variables and they show they're in the correct form (YYYY-MM-DD) to compare within the database but no results are returning.
Any help would be greatly appreciated. Many thanks in return.
Well, assuming that the mysql database has the same date that your server, you could let the mysql database do all the date calculations.
A little something like this:
SELECT *
FROM listing
WHERE dd_end BETWEEN CURDATE() AND (CURDATE() + INTERVAL 14 DAY)
On the other hand, i think Paul S's answer may fix your problem.
Edit:
You forgot to call mysql_query before the mysql_fetch_assoc() function.
$result = mysql_query($q);
while ($row = mysql_fetch_assoc($result))
{
$listing_id = $row['listing_id'];
echo "$listing_id";
}
If dd_end is a date you may want to read a certain section on the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between
For best results when using BETWEEN with date or time values, use
CAST() to explicitly convert the values to the desired data type.
Examples: If you compare a DATETIME to two DATE values, convert the
DATE values to DATETIME values. If you use a string constant such as
'2001-1-1' in a comparison to a DATE, cast the string to a DATE.
May this is the right way ?
$start = date("Y-m-d", strtotime('+14 day' . $date));
Read:
http://php.net/manual/en/function.strtotime.php
strtotime has a second argument.
$format = 'Y-m-j';
$date = date ( $format );
$new = date ( $format, strtotime ( '+14 day' . $date ) );
$start = date("Y-m-d", strtotime($new));
Should be:
$new = strtotime('+14 day', time());
$start = date("Y-m-d", $new);
$today = date('Y-m-d');
$q = mysql_query("SELECT * FROM listing WHERE dd_end BETWEEN '".$today."' AND '".$start."'");
while($row = mysql_fetch_assoc($q)){
$listing_id = $row['listing_id'];
echo "$listing_id";
}

change dd/mm/yy date format to yy/mm/dd using php

I'm having date 20/12/2001 in this formate . i need to convert in following format 2001/12/20 using php .
$var = explode('/',$date);
$var = array_reverse($var);
$final = implode('/',$var);
Your safest bet
<?php
$input = '20/12/2001';
list($day, $month, $year) = explode('/',$input);
$output= "$year/$month/$day";
echo $output."\n";
Add validation as needed/desired. You input date isn't a known valid date format, so strToTime won't work.
Alternately, you could use mktime to create a date once you had the day, month, and year, and then use date to format it.
If you're getting the date string from somewhere else (as opposed to generating it yourself) and need to reformat it:
$date = '20/12/2001';
preg_replace('!(\d+)/(\d+)/(\d+)!', '$3/$2/$1', $date);
If you need the date for other purposes and are running PHP >= 5.3.0:
$when = DateTime::createFromFormat('d/m/Y', $date);
$when->format('Y/m/d');
// $when can be used for all sorts of things
You will need to manually parse it.
Split/explode text on "/".
Check you have three elements.
Do other basic checks that you have day in [0], month in [1] and year in [2] (that mostly means checking they're numbers and int he correct range)
Put them together again.
$today = date("Y/m/d");
I believe that should work... Someone correct me if I am wrong.
You can use sscanf in order to parse and reorder the parts of the date:
$theDate = '20/12/2001';
$newDate = join(sscanf($theDate, '%3$2s/%2$2s/%1$4s'), '/');
assert($newDate == '2001/12/20');
Or, if you are using PHP 5.3, you can use the DateTime object to do the converting:
$theDate = '20/12/2001';
$date = DateTime::createFromFormat('d/m/Y', $theDate);
$newDate = $date->format('Y/m/d');
assert($newDate == '2001/12/20');
$date = Date::CreateFromFormat('20/12/2001', 'd/m/Y');
$newdate = $date->format('Y/m/d');

Categories