I have a textbox on one of my forms, the user enters a date in the form of dd/mm/yy
but when i try to insert it into one of my tables in my database, it enters it as
0000-00-00. how can I fix this? I want it to show on this format on my database dd/mm/yy
this is my following insert where $start is the data variable
$query = "INSERT INTO paycheck (payCheckId,jobId,payRate,jobLocation,hoursWorked,startPeriod,empId)
VALUES('','$job_id','$pay_rate','$job_location','$hours','$start','$userId')";
$result = mysqli_query($db, $query); //we make the query
You can chose either MySQL to do this, or you can have PHP do it for you.
For MySQL related solution, please check STR_TO_DATE() function and for PHP the function date() does it.
Usage in STR_TO_DATE() is:
STR_TO_DATE( '$startPeriod', '%d/%m/%Y' )
Hence, the query will be:
INSERT INTO paycheck (payCheckId, jobId, payRate,
jobLocation, hoursWorked, startPeriod, empId)
VALUES( '', '$job_id', '$pay_rate',
'$job_location', '$hours',
STR_TO_DATE( '$startPeriod', '%d/%m/%Y' ), '$userId')
You need to reformat your date so MySQL can read it. The format the database saves to is yyyy-mm-dd. If you would like to display the date in the format it originally came in, simply use the date() function like so: $date = date("d/m/y", strtotime($dateFromDB));
This might be a long winded way of doing it, and there are better ways out there however, you can create your own function to reformat it:
function reformatDate($incorrectFormat) {
list($d, $m, $y) = explode("/", $input);
$todaysYearBeginning = substr(0, 2, date("Y", time()));
if(strlen($d == 1) {
$d = "0" . $d;
}
if(strlen($m == 1) {
$m = "0" . $m;
}
if(strlen($y == 1) {
$y = "0" . $y;
}
return $todaysYearBeginning . $y . "-" . $m . "-" . $d;
}
echo reformatDate("dd/mm/yy");
Following on from Dream Eater's answer, you can use DateTime::CreateFromFormat like so:
$oldDate = DateTime::createFromFormat('d/m/y', $dateFromDB);
$newDate = $oldDate->format('Y-m-d');
Related
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);
?>
I have an availability calendar in which I am currently adding in dates one by one, and using a mysql query to determine if there exists a row with a certain date and changing the class of the day to "booked" (Red).
I would like to enter in a range into my form, and process it through php (or mysql) into multiple, individual dates. My date format is M/D/YYYY, or MM/DD/YYYY, both are accepted. Unfortunately, when I built my calendar, I did not use the date format in sql for entries, but used varchar.
Is there a way to enter into my form for example 1/1/2014-1/3/2014 and have php convert that to 1/1/2014, 1/2/2014, 1/3/2014, and then have a mysql INSERT query to insert multiple values at once?
if (empty($_POST) === false && empty($errors) === true) {
$adcp_data = array(
'date' => $_POST['date'],
'customer' => $_POST['customer'],
'notes' => $_POST['notes'],
);
insert_adcp($adcp_data);
header('Location: adcp.php?success');
exit();
the insert_adcp function looks like this:
function insert_adcp ($adcp_data) {
array_walk($adcp_data, 'array_sanitize');
$fields = '`' . implode('`, `', array_keys($adcp_data)) . '`';
$data = '\'' . implode('\', \'', $adcp_data) . '\'';
mysql_query("INSERT INTO `adcp` ($fields) VALUES ($data)");
}
My workaround and last resort will be to add multiple text inputs and just add multiple dates manually so I only have to submit once. But a range is so much faster!
As a last note, if I could have those multiple entries keep the "customer" and "notes" values for each date in the range that would be amazing. I am prepared to lose those fields though to make this work. Thanks
Something like:
$day = new DateTime($_POST['range_start']);
$end = new DateTime($_POST['range_end']);
$all_dates = array();
while ($day <= $end){
$all_dates[] = $day;
$day->add(new DateInterval('P1D'));
}
That will give you an array of DateTime objects each of which represents a day in your range. You can get each object back into a string by calling DateTime::format() and passing 'm/d/Y' as the format string.
As for getting multiple entries into MySQL, the INSERT syntax allows INSERT INTO table (column) VALUES (row1), (row2), ... (rowN)
(this is clearly not not tested or the final code you would use -- just written into this web form from memory ... you'll have to write it out properly with input sanitation and range checking and whatnot.)
Check if the value from the input match your range format, capture the parts and generate the from and to dates.
if (preg_match('%\A(?<fromMonth>\d{1,2})/(?<fromDay>\d{1,2})/(?<fromYear>\d{4})-(?<toMonth>\d{1,2})/(?<toDay>\d{1,2})/(?<toYear>\d{4})\Z%', $str, $res)) {
$dates['from'] = mktime(0, 0, 0, $res['fromMonth'], $res['fromDay'], $res['fromYear']);
$dates['to'] = mktime(0, 0, 0, $res['toMonth'], $res['toDay'], $res['toYear']);
}
Generate the range between from and to dates.
for ($date = $dates['from']; $date <= $dates['to']; $date = strtotime('+1 day', $date) ){
$dates['range'][] = date('m-d-Y', $date);
}
I think, strtotime is more usable for your case. You can found definition at php.net site:
http://php.net/manual/en/function.strtotime.php
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...
Got stuck in a complex or maybe stupid problem. I am getting a query from mysql, and then trying to compare a date column with a PHP data which i formatted to the same format i.e "Y-m-d" it always results in no match, although i see there is a match.. and it gets the right result set too.
<?php
date_default_timezone_set('America/Los_Angeles'); // set timezone to our timezone
$constantTime = time(); // get value of time in constant
$appDate = date("Y-m-d", $constantTime); //that defines php time variable -
$queryDate = "SELECT * FROM date WHERE date='$appDate'";
$resultDate = mysql_query($queryDate) or die("Sorry Website Under Maintainence");
$recordDate = mysql_fetch_array($resulDate);
if ($appDate == date("Y-m-d", strtotime($recordDate['date']))) {
echo "MATCH ";
$dateID = $recordDate['dateID'];
} else {
mysql_query("insert into date(date) values('$appDate')")or die("Database write error1");
$resultDate = mysql_query($queryDate) or die("Sorry Website Under Maintainence");
$recordDate = mysql_fetch_array($resultDate);
echo "NO MATCH ";
$dateID = $recordDate['dateID'];
}
This is always triggering the else, i tried === instead of ==, i tried strcmp
As i assume you're comparing datetime field, you have two possibilities:
Cast field to date:
$queryDate = "SELECT * FROM your_table WHERE date(your_date_field) = date('$appDate')";
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date
or
Modify your date format to be ISO compatible:
$appDate = date("Y-m-d H:i:s", $constantTime); //it defines date in format 2015-03-14 15:00:00
$queryDate = "SELECT * FROM your_table WHERE your_date_field='$appDate'";
See also this question
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";
}