Adding current date to DATE table mysql ERROR - php

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);
?>

Related

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');
?>

Storing date as text in database but need to find records between two dates?

I am storing dates as VARCHAR in mysql tables. I actually have a invoice table that stores invoice details along with its date. I store those dates with this function of php in VARCHAR column.
date("d/m/y")
Now i need to generate reports of sales like from 4/5/2012 to 4/5/2013. I am confused as to how to find the date range. Please guide.
I am using codeigniter.
If it's dates why not store as date? You could now add another column, then with a script or program populate this new column with the parsed and recomposed dates. Thus, your future queries can work with a date data type.
Use MySQL's built in string to date parsing
SELECT * FROM your_table WHERE STR_TO_DATE(`date_column`,'%d/%m/%Y') BETWEEN '2012-04-05' to '2013-04-05'
or in CI ActiveRecord
$this->db->select('*')
$this->db->from('your_table');
$this->db->where('STR_TO_DATE(`date_column`,"%d/%m/%Y") >=', '2012-04-05');
$this->db->where('STR_TO_DATE(`date_column`,"%d/%m/%Y") <=', '2013-04-05');
$query = $this->db->get();
$results = $query->result();
I'm providing a suggestion here rather than an explicit answer.
Do you have any specific reason for storing dates as varchar. Storing as integer at least makes more sense than varchar. Could you possibly rework your database? Store dates as dates yyyy-mm-dd. Or is that completely impossible at this time?
If you wanted the above format as display, you could
<?php list($year, $month, $day) = explode("-", $date) ?>
and reorder for display as
<?php echo $day."/".$month."/".$year ?>
If it is completely impossible to rework the db, then use MYSQL STR_TO_DATE
Please see if this link could be of help: http://www.w3resource.com/mysql/date-and-time-functions/mysql-str_to_date-function.php
[EDIT]
<?php
$date_from = '26/02/13';
$date_to = '26/02/13';
//Because STR_TO_DATE would create a valid date from what you have in varchar.
list($day, $month, $year) = explode("/", $date_from);
$date_from = $year . "-" . $month . "-" . $day;
list($day, $month, $year) = explode("/", $date_to);
$date_to = $year . "-" . $month . "-" . $day;
$this->db->where('STR_TO_DATE(`date`,"%d/%m/%y") >=', $date_from);
$this->db->where('STR_TO_DATE(`date`,"%d/%m/%y") <=', $date_to);
$query = $this->db->get('TABLENAME');
//use your result here
?>
i think you can get the date from char to timestamp , of course, you need to do some format for your date...
here is some sample...
$senttime = strtotime($date . ' ' . $hour . ':' . $min . ':00');
$exdate = strtotime($exdate . ' 00:00:00');
$now = strtotime("now");
if ($now < $senttime && $senttime < $exdate) {...
than you can get the range...

convert string into date

Hi I know this question is a bit trivial. I googled it but could not find the exact problem anywhere.
I have a string which contains a application filling date how can I convert this string into date
$appln_filling_date = '20020315';
The type of appln_filling_date is string I want to convert its type to date and want the data remain the same. The field in the database has a type date.
EDIT
This is what I am trying to do
$appln_filling_date = strtotime($appln_data['bibliographic-data']['application-reference']['document-id']['1']['date']['$']);
$appln_filling_date = date('Y-m-d', $appln_filling_date);
If your date is in some standard date format use this example:
$d = new DateTime('20020315');
echo $d->format('Y-m-d');
# or [if you do not have DateTime, which is in php >= 5.2.0]
$t = strtotime('20020315');
echo date('Y-m-d', $t);
If your date is not in some standard format use this example:
$d = DateTime::createFromFormat('d . Y - m', '15 . 2002 - 03');
echo $d->format('Y-m-d');
$date = DateTime::createFromFormat('Ymd', $appln_filling_date);
This worked for me like a charm
$appln_filling_date = $appln_data['bibliographic-data']['application-reference']['document-id']['1']['date']['$'];
$appln_filling_date = date_create(date('Y-m-d', $appln_filling_date));
Thanks for the down voting

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');

strtotime php mysql

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";

Categories