Trouble inserting a date into a MySql database - php

I've looked at several of the threads that have to do with this issue and still can't figure out what's going wrong with my code.
I'm bring a date field from my form that is in this format "mm-dd-yyyy", when I bring it to my code to update the date of birth field as "yyyy-dd-mm" I use the following
$birth=$_POST['dateBorn'];
$dateB = date('Y-d-m',strtotime($birth));
$finaldateB = ($dateB === false) ? '0000-00-00' : date('Y-d-m',strtotime($dateB));
When I echo the values of the variables (using a date of birth of 11-23-2012) I see the following values for them birth = 11-23-2012, dateB = 1969-31-12, finaldateB = 1969-31-12
I'm obviously doing something incorrect and haven't been able to locate where
TIA
In order to get things to function, I've at least discovered a work-around that may not be elegant but gives me the results I need for now
$dateB = $birth;
$dateborn_a=explode("-",$birth);
$yearborn = $dateborn_a[2];
$dayborn = $dateborn_a[1];
$monthborn = $dateborn_a[0];
$dateOfBirth=$yearborn."-".$monthborn."-".$dayborn;
And then use the value in $dateOfBirth to update the table. It's worked for all the records I've tested it on so far.

$dateB = date('Y-d-m',strtotime($birth));
here
y is for year
d is for day
m is for month
so formate will be yyyy-dd-mm
try
$dateB = date('Y-m-d',strtotime($birth));

You're using Y-d-m instead of Y-m-d. MySQL's date format should be YEAR-MONTH-DAY. Using
$dateB = date('Y-m-d',strtotime($birth));
should fix it.

Related

Search date in mysql date time column

I have a table in MYSQL database with a column db_date with type is datetime ex:2016-10-20 01:05:00
I use a PHP code to search different thing the date is one of them for that i use a date picker have the date like this 10/21/2016 m/d/Y
for that i use this to transform this form to the form in database
STR_TO_DATE('".$date."','%m/%d/%Y')
The Problem is that when i use db_date= STR_TO_DATE('".$date."','%m/%d/%Y') it give only the date that have hour and minutes and second 00:00:00
but i want all the date ex: if i choose 10/20/2016 i want all date with different time in database be selected
i tried to use the date function in mysql but i didn't have result
date(STR_TO_DATE('".$date."','%m/%d/%Y'))
And also i tried to use the DATE_FORMAT(STR_TO_DATE('".$date."','%m/%d/%Y'))
and i didn't have a result
the query will be like this $query=SELECT * FROM tbl_staff {$sql}
and this is the code
$q = array();
$sql = "";
if(isset($_POST['txt_date']) && !empty($_POST['txt_date'])){
$date = mysqli_real_escape_string($conn,$_POST['txt_date']);
$q[] = " db_date=STR_TO_DATE('".$date."','%m/%d/%Y') and db_status!='Done' AND db_status!='Cancelled'";
}
How can i solve this problem ?!
First of all you can use format in datapicker to customise the date :
$('#date').datepicker({format: 'yyyy-mm-dd'});
And for your sql query do (use date() for db_date)
$q[] = " DATE(db_date)= $date and db_status!='Done' AND db_status!='Cancelled'";

Incorrect value of datetime PHP and MySQL

In my site, I have a bootstrap datepicker which allows user to pick date in format of MM/DD/YYYY (e.g: 05/12/2014). Then when this data is submitted, I used the following PHP code to convert it into Datetime type, then insert into start_date (DATETIME datatype) column in MySQL .
$start_date = date('Y-m-d', $_POST['start_date']);
the insert query in PHP does nothing with reformatting the date. It just simply insert into corresponding column.
However, instead of inserting '2014-05-12', the value inserted into database is '1970-01-01'. That's so weird to me. Can anybody tell me what's wrong here. Is this that I used incorrect PHP function or incorrect timezone setting or ...
Just do this:
$start_date = date('Y-m-d', strtotime($_POST['start_date']));
You could also use strtotime() on your $_POST.
$start_date = date('Y-m-d', strtotime('05/12/2014'));
try to use
$date = str_replace('/', '-', $_POST['start_date']);
$start_date = date('Y-m-d', strtotime($date));
For more :- Converting between illogically formatted dates (changing /slash/ to -dash- )

PHP displaying date is one day forward after format

When I retrieve a date from a my_sqli query and format it it becomes one day forward. The date is saving correctly to the server, and echoing it before the new format is correct.
$date = "SELECT date FROM blogtable WHERE id = $artID";
$dateEx = mysqli_query($con, $date);
while($dateGet = mysqli_fetch_array($dateEx))
{
//This is in YYYY-mm-dd
$dateGet['date'];//If I echo this, it is correct
}
$source = $dateGet;
$newDate = new DateTime($source);
echo $newDate->format('M-d-Y');
So for example if I tried to use it today(the 24th), it would save correctly, but after the format, display as the 25th.
Wrikken's suggestion worked, changing the statement in the while to $source=$dateGet['date']; and deleting the $source = $dateGet;.

check if datetime from sql is today

I have a date returned from an sql query (a datetime type field) and want to compare it to today's date in PHP. I have consulted php manual and there are many ways to do it. I finally came up with a solution comparing strings, but I would like to know if there are either any 'better' (best practice), cleaner or faster ways to do it. This is my solution:
// $sql_returned_date='2008-10-17 11:20:04'
$today = new DateTime("now");
$f_today=$today->format('Y-m-d'); //formated today = '2011-03-09'
$sql_date=substr($sql_returned_date,0,9); //I get substring '2008-10-17'
if($f_today==$sql_date)
{
echo "yes,it's today";
}else{
echo "no, it's not";
}
thanks
Seriously guys?
//$mysql_date_string= '2013-09-20' OR '2013-09-20 12:30:23', for example
$my_date = new DateTime($mysql_date_string);
if($my_date->format('Y-m-d') == date('Y-m-d')) {
//it's today, let's make ginger snaps
}
You could factor this into the data returned from your database query:
SELECT `DateOnDB`,
DATE(`DateOnDB`) = DATE(CURDATE()) AS isToday
FROM `dbTable`
and simply use PHP to test the value of the isToday column
Excuse me for being a question-digger, but I was trying to achieve the same thing, and I found a simple solution - if you want to select only rows with today's date you can do :
WHERE DATE(datetime_column)=CURDATE()
in your mySQL query syntax.
You'd have three solutions :
Working with strings, like you are doing ; which seems like a solution that works ; even if it doesn't feel clean.
Working with timestamps, using strtotime() and time() ; which is a bad idea : UNIX Timestamps only work for dates that are greater than 1970 and lower than 2038
Working with DateTime everywhere ; which would both work and feel clean.
If I need to make any calculation on the PHP-side, I would probably go with the third solution -- but the first one would be OK in most cases, I suppose.
As a sidenote : instead of formating your date to Y-m-d, you could check if it's :
Greater of equal than today
Less than tomorrow.
If SQL returned date is in this format 2011-03-09 (date format without timing),
$sqlret = "2011-03-05";
$curdate = date('Y-m-d');
echo $diff = strtotime($curdate) - strtotime($sqlret);
echo $no_diff = $diff/(60*60*24);
If the date with time like:
$sqlret = "2011-03-05 12:05:05",
Just make your current date format also like that:
$curdate = date('Y-m-d H:i:s');
If it doesn't satisfies your need, ask your question with some example.
You can use new DateTime php Object that way.
$date1 = new DateTime('2012-01-21');
$date2 = new DateTime ( 'now');
$interval = $date1->diff($date2);
if( $interval->format('%R%a ') == 0){
echo 'it s today';
}
I'd do that:
# SQL
SELECT DATE_FORMAT(date_col, "%Y-%m-%d") AS created_at FROM table
# PHP
if ( date('Y-m-d') == $sql_date ) { // assuming $sql_date is SQL's created_at
echo 'today';
}
$time = //your timestamp
$start = mktime(0,0,0,date("j"),date("n"),date("Y"));
$end = mktime(23,59,0,date("j"),date("n"),date("Y"));
if($time > $start && $time < $end){
//is today
}

PHP/MySQL: Convert from YYYY-MM-DD to DD Month, YYYY?

I have in a MySQL table a DATE column that represents the date in this format: YYYY-MM-DD.
I wanto to retrieve the date from the database using PHP but display it like this: DD Month, YYYY.
From '2009-04-13' to '13 April, 2009' for example.
Witch is the best way to do it?? ( I know how to get the date from the DB. I only need to know how to convert it)
I also need to display the month names in Spanish. There is a way to do it without translating each month using strplc or something like that??
I'm new to programming, please be detailed.
Thanks!!!
Refer to DATE_FORMAT() function in MySQL. I guess that's the best way for you to do it.
Also, you can make this:
Fetch your date from DB
Use strtotime in PHP, to convert to unix time
Then format the time using date.
By using date() you'll be able to get months names in Spanish when you set your locale in PHP with setlocale.
You could also skip the strtotime() part by using UNIX_TIMESTAMP(date) in your MySql select. But remember that this is a MySQL specific function and may not be be portable in the future.
Execute following MySQL queries:
SET lc_time_names = 'es_ES';
SELECT DATE_FORMAT(t.date,'%e de %M, %Y') FROM your_table t ...
With MySQLi it'll be:
$mysqli->query("SET lc_time_names = 'es_ES'");
$stmt = $mysqli->prepare("SELECT DATE_FORMAT(t.date,'%e de %M, %Y') FROM your_table t ...where id = ?");
...
Another option not yet mentioned:
SQL:
SELECT UNIX_TIMESTAMP(date) FROM table
PHP:
print date('your format', $timestamp_from_the_db);
Personally, I like to use integer data types in MySQL for date storage in the UNIX timestamp format. I leave all the processing of that integer up to PHP. Keeping tables and queries as simple as possible has always served me well. Predominantly, in the code I write, dates have some sort of calculation done to them. This is all done on the PHP side and always in the UNIX timestamp format. Storing or retrieving the dates in anything other than the UNIX timestamp format just means another step for errors to creep in and makes the query less modular. How a date is formatted is best left up until the last minute before it's displayed. It's just my opinion, but unless there are extreme circumstances where you can't process the DB value after extraction, a date shouldn't be formatted SQL-side.
A simplified example:
<?php
$date = now();
$dueDate = $date + 60*60*24*7; // One week from now
$sqlInsert = "INSERT INTO reports SET `dueDate` = $date";
$resInsert = mysql_query( $sqlInsert );
$sqlSelect = "SELECT `dueDate` FROM reports";
$resSelect = mysql_query( $sqlSelect );
$rowSelect = mysql_fetch_array( $resSelect );
$DB_dueDate = $rowSelect['dueDate'];
$daysUntilDue = ( $DB_dueDate - now() ) / 60*60*24;
$formattedDueDate = date( "j F, Y", $DB_dueDate );
?>
The report is due on <?=$formattedDueDate?>. That is <?=$daysUntilDue?> from now.
Simplest way is to use the strtotime() function to normalize the input to UNIX timestamp.
Then use the date() function to output the date in any format you wish. Note that you need to pass the UNIX timestamp as the second argument to date().
This will help you to convert as you want:
$dob ='2009-04-13';
echo date('d M Y', strtotime($dob));
$origDate = "2018-04-20";
$newDate = date("d-m-Y", strtotime($origDate));
echo $newDate;

Categories