I'm using jQuery datepicker
the format of the datepicker is this 08/25/2012
I have errors when inserting to my database it inserts only 0000-00-00 00 00 00
My code is:
<?php
$id = $_POST['id'];
$name = $_POST['name'];
$date = $_POST['date'];
$sql = mysql_query( "INSERT INTO user_date VALUE( '', '$name', '$date')" ) or die ( mysql_error() );
echo 'insert successful';
?>
I'm sure my insert is correct.
As stated in Date and Time Literals:
MySQL recognizes DATE values in these formats:
As a string in either 'YYYY-MM-DD' or 'YY-MM-DD' format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example, '2012-12-31', '2012/12/31', '2012^12^31', and '2012#12#31' are equivalent.
As a string with no delimiters in either 'YYYYMMDD' or 'YYMMDD' format, provided that the string makes sense as a date. For example, '20070523' and '070523' are interpreted as '2007-05-23', but '071332' is illegal (it has nonsensical month and day parts) and becomes '0000-00-00'.
As a number in either YYYYMMDD or YYMMDD format, provided that the number makes sense as a date. For example, 19830905 and 830905 are interpreted as '1983-09-05'.
Therefore, the string '08/25/2012' is not a valid MySQL date literal. You have four options (in some vague order of preference, without any further information of your requirements):
Configure Datepicker to provide dates in a supported format using an altField together with its altFormat option:
<input type="hidden" id="actualDate" name="actualDate"/>
$( "selector" ).datepicker({
altField : "#actualDate"
altFormat: "yyyy-mm-dd"
});
Or, if you're happy for users to see the date in YYYY-MM-DD format, simply set the dateFormat option instead:
$( "selector" ).datepicker({
dateFormat: "yyyy-mm-dd"
});
Use MySQL's STR_TO_DATE() function to convert the string:
INSERT INTO user_date VALUES ('', '$name', STR_TO_DATE('$date', '%m/%d/%Y'))
Convert the string received from jQuery into something that PHP understands as a date, such as a DateTime object:
$dt = \DateTime::createFromFormat('m/d/Y', $_POST['date']);
and then either:
obtain a suitable formatted string:
$date = $dt->format('Y-m-d');
obtain the UNIX timestamp:
$timestamp = $dt->getTimestamp();
which is then passed directly to MySQL's FROM_UNIXTIME() function:
INSERT INTO user_date VALUES ('', '$name', FROM_UNIXTIME($timestamp))
Manually manipulate the string into a valid literal:
$parts = explode('/', $_POST['date']);
$date = "$parts[2]-$parts[0]-$parts[1]";
Warning
Your code is vulnerable to SQL injection. You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
Also, as stated in the introduction to the PHP manual chapter on the mysql_* functions:
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
You appear to be using either a DATETIME or TIMESTAMP column for holding a date value; I recommend you consider using MySQL's DATE type instead. As explained in The DATE, DATETIME, and TIMESTAMP Types:
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
You should consider creating a timestamp from that date witk mktime()
eg:
$date = explode('/', $_POST['date']);
$time = mktime(0,0,0,$date[0],$date[1],$date[2]);
$mysqldate = date( 'Y-m-d H:i:s', $time );
$date_field = date('Y-m-d',strtotime($_POST['date_field']));
$sql = mysql_query("INSERT INTO user_date (column_name,column_name,column_name) VALUES('',$name,$date_field)") or die (mysql_error());
You must make sure that the date format is YYYY-MM-DD on your jQuery output. I can see jQuery returns MM-DD-YYYY, which is not the valid MySQL date format and this is why it returns an error.
To convert it to the right one you could do this:
$dateFormated = split('/', $date);
$date = $dateFormated[2].'-'.$dateFormated[0].'-'.$dateFormated[1];
Then you will get formatted date that will be valid MySQL format, which is YYYY-MM-DD, i.e. 2012-08-25
I would also recommend using mysql_real_escape_string as you insert data into database to prevent SQL injections as a quick solution or better use PDO or MySQLi.
Your insert query using mysql_real_escape_string should rather look like this:
$sql = mysql_query( "INSERT INTO user_date VALUE( '', '" .mysql_real_escape_string($name). "', '" .mysql_real_escape_string($date). "'" ) or die ( mysql_error() );
Get a date object from the jquery date picker using
var myDate = $('element').datepicker('getDate')
For mysql the date needs to be in the proper format. One option which handles any timezone issues is to use moment.js
moment(myDate).format('YYYY-MM-DD HH:mm:ss')
The simplest method is
$dateArray = explode('/', $_POST['date']);
$date = $dateArray[2].'-'.$dateArray[0].'-'.$dateArray[1];
$sql = mysql_query("INSERT INTO user_date (column,column,column) VALUES('',$name,$date)") or die (mysql_error());
HTML:
<div class="form-group">
<label for="pt_date" class="col-2 col-form-label">Date</label>
<input class="form-control" type="date" value=<?php echo date("Y-m-d") ;?> id="pt_date" name="pt_date">
</div>
SQL
$pt_date = $_POST['pt_date'];
$sql = "INSERT INTO `table` ( `pt_date`) VALUES ( '$pt_date')";
Suppose you receive a Christmas date:
December 25, 2021 (25 de Diciembre del año 2021) in string format: "d-m-Y" for example "12-25-2021". First create a valid DateTime object from the received format:
var_dump(DateTime::createFromFormat("d-m-Y","25-12-2021", new DateTimeZone("America/Argentina/Buenos_Aires")));
This generates as output:
object(DateTime)#2 (3) {
["date"]=>
string(26) "2021-12-25 10:21:11.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(30) "America/Argentina/Buenos_Aires"
}
Now to get the date field from the DateTime object ready to go using format("Y-m-d H:i:s")):
var_dump(DateTime::createFromFormat("d-m-Y","25-12-2021",new DateTimeZone("America/Argentina/Buenos_Aires"))->format("Y-m-d H:i:s"));
This generates as output a ready to insert value:
string(19) "2021-12-25 10:56:30"
In summary now you can insert a formated date ('DD-MM-YYYY') in MySQL like this:
<?php
//string input post like "25-12-2021"
$date_input = $_POST['date_input'];
//create DateTime object
$date_time_obj=DateTime::createFromFormat("d-m-Y","25-12-2021",new DateTimeZone("America/Argentina/Buenos_Aires"));
//format date ready to insert as string at MySQL
$str_date=$date_time_obj->format("Y-m-d H:i:s");
?>
Now run directly from PHP to MySQL as a query:
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
//verify connection
if (mysqli_connect_errno()) {
printf("Error de conexión: %s\n", mysqli_connect_error());
exit();
}
//prepare the query to execute
$stmt = $mysqli->prepare("INSERT INTO table_example (DATE_FIELD) VALUES (?)");
//prevent sql injection
$stmt->bind_param('s', $str_date);
//execute prepared statements
$stmt->execute ();
?>
These days, I am not good with dates. Thanks to the following work, I can print the dates in the format I want.
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$scr = strtotime($year . '-' . $month . '-' . $day);
$gelis_tarihi = date('Y-m-d', $scr);
$yil = $_POST['yil'];
$ay = $_POST['ay'];
$gun = $_POST['gun'];
$birlestir = strtotime($yil . '-' . $ay . '-' . $gun);
$gelis_tarihi = date('Y-m-d', $birlestir);
Try Something like this..
echo "The time is " . date("2:50:20");
$d=strtotime("3.00pm july 28 2014");
echo "Created date is " . date("d-m-y h:i:sa",$d);
First of all store $date=$_POST['your date field name'];
insert into **Your_Table Name** values('$date',**other fields**);
You must contain date in single cote (' ')
I hope it is helps.
Related
So Im scraping a website for data, and one piece of data that im scraping is the date of certain items.
The date of the items comes in the format "Wed 11th March, 2015".
I have been trying to then insert this into my mysql database. The structure of the database contains a column with "datapublished" as a Timestamp,
`feeddatapublished` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)
When updating the rest of the columns with the data it updates fine with the following code
$stmt = $dbh->prepare("INSERT INTO `feedsdata` (`id`, `feedid`, `feedurl`, `feedsummary`, `feedtitle`, `feeddatapublished`) VALUES (NULL, :feed_id, :feed_url, :feed_summary, :title, :datapublished)");
$stmt->bindParam(':feed_id', $feed_id);
$stmt->bindParam(':feed_url', $feed_url);
$stmt->bindParam(':feed_summary', $feed_summary);
$stmt->bindParam(':title', $feed_title);
$stmt->bindParam(':datapublished',$datepublished);
$stmt->execute();
I converted the string from the feed before passing it to be inserted with
$datepublished = strtotime(scrape_between($separate_result, "<span class=\"date\">", "</span>"));
scrape_between is a function I use for the scraping.
When echoing out the $datepublished I get the timestamp 1458155700, which isnt the correct timestamp from what i can see.
All other columns are updating as required, the only one which isnt is the datepublished one.
My two questions are
Is the reason its not updating because im passing a malformed timestamp to the mysql database
How can I generate a better timestamp from the format above, Ive checked the date function but I cant seem to get it to work.
The MySQL timestamp format is 2016-02-13 15:48:29 or Y-m-d H:i:s convert your unix timestamp to that format first, and then MySQL will accept it.
Either with
<?php
$datapublished = date("Y-m-d H:i:s", strtotime(scrape_between($separate_result, "<span class=\"date\">", "</span>")));
OR
your query to
$stmt = $dbh->prepare("INSERT INTO `feedsdata` (`id`, `feedid`, `feedurl`, `feedsummary`, `feedtitle`, `feeddatapublished`)
VALUES (NULL, :feed_id, :feed_url, :feed_summary, :title, from_unixtime(:datapublished))");
the problem is that strtotime is not smart enough to recognise the string so its best guess is 1458155700.
you can add an additional step to clean the date:
$scrape = scrape_between(...);
$cleanDate = preg_replace(
'/[a-z]+ ([0-9]{1,2})[a-z]+ ([a-z]+), ([0-9]{4})/i',
'$1 $2 $3',
$scrape
);
$datepublished = strtotime($cleanDate);
the preg_replace function uses a regular expression to remove the unnecessary parts.
If you know the date format used on the webpage you're scraping and it stays constant, you can use DateTime::createFromFormat() for safer and more controlled date parsing.
<?php
$datestring = "Wed 11th March, 2015";
$date = DateTime::createFromFormat("D dS F, Y", $datestring);
// Reset hours, minutes and seconds - otherwise the current time is used
$date->setTime(0, 0, 0);
// Format for MySQL database insertion
$datepublished = $date->format("Y-m-d H:i:s");
I have the following problem. I have a string, which contains time and date as follows:
dd/MM/yy hh:mm:ss
This I have in PHP. And then I have a MySQL database, which has a column of a datetime format, where I need to insert this value. Obviously the problem is, that the format is different, so instead of the actual date, it results in a field "0000-00-00 00:00:00".
Could you please help me with converting this string and then inserting it properly into MySQL?
For the MySQL I use the standard INSERT INTO command.
From the DATETIME documentation:
MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format.
I'd use PHP's DateTime class and DateTime::createFromFormat() method, and convert the data into a MySQL-compatible date string, like so:
$date = DateTime::createFromFormat('d/m/Y H:i:s', $yourDateString);
$dateToBeInserted = $date->format('Y-m-d H:i:s');
Write a function to convert date,
function sqldate($date)
{
$sql_date = date('Y-m-d H:i:s',strtotime($date));
return $sql_date;
}
And your query look like,
$query = "INSERT INTO tableName (dateColumn) VALUES('".sqldate($date)."') ";
You can convert it using STR_TO_DATE() along with your INSERT statement, eg.
INSERT INTO tableName (dateColumn)
VALUES(STR_TO_DATE('dd/MM/yy hh:mm:ss','%d/%m/%y %H:%i:%s'))
SQLFiddle Demo
Try this:
$parsedDate = date('Y-m-d H:i:s', strtotime($yourDate));
// Insert $parsedDate into your table column Date
I'm using jQuery datepicker
the format of the datepicker is this 08/25/2012
I have errors when inserting to my database it inserts only 0000-00-00 00 00 00
My code is:
<?php
$id = $_POST['id'];
$name = $_POST['name'];
$date = $_POST['date'];
$sql = mysql_query( "INSERT INTO user_date VALUE( '', '$name', '$date')" ) or die ( mysql_error() );
echo 'insert successful';
?>
I'm sure my insert is correct.
As stated in Date and Time Literals:
MySQL recognizes DATE values in these formats:
As a string in either 'YYYY-MM-DD' or 'YY-MM-DD' format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example, '2012-12-31', '2012/12/31', '2012^12^31', and '2012#12#31' are equivalent.
As a string with no delimiters in either 'YYYYMMDD' or 'YYMMDD' format, provided that the string makes sense as a date. For example, '20070523' and '070523' are interpreted as '2007-05-23', but '071332' is illegal (it has nonsensical month and day parts) and becomes '0000-00-00'.
As a number in either YYYYMMDD or YYMMDD format, provided that the number makes sense as a date. For example, 19830905 and 830905 are interpreted as '1983-09-05'.
Therefore, the string '08/25/2012' is not a valid MySQL date literal. You have four options (in some vague order of preference, without any further information of your requirements):
Configure Datepicker to provide dates in a supported format using an altField together with its altFormat option:
<input type="hidden" id="actualDate" name="actualDate"/>
$( "selector" ).datepicker({
altField : "#actualDate"
altFormat: "yyyy-mm-dd"
});
Or, if you're happy for users to see the date in YYYY-MM-DD format, simply set the dateFormat option instead:
$( "selector" ).datepicker({
dateFormat: "yyyy-mm-dd"
});
Use MySQL's STR_TO_DATE() function to convert the string:
INSERT INTO user_date VALUES ('', '$name', STR_TO_DATE('$date', '%m/%d/%Y'))
Convert the string received from jQuery into something that PHP understands as a date, such as a DateTime object:
$dt = \DateTime::createFromFormat('m/d/Y', $_POST['date']);
and then either:
obtain a suitable formatted string:
$date = $dt->format('Y-m-d');
obtain the UNIX timestamp:
$timestamp = $dt->getTimestamp();
which is then passed directly to MySQL's FROM_UNIXTIME() function:
INSERT INTO user_date VALUES ('', '$name', FROM_UNIXTIME($timestamp))
Manually manipulate the string into a valid literal:
$parts = explode('/', $_POST['date']);
$date = "$parts[2]-$parts[0]-$parts[1]";
Warning
Your code is vulnerable to SQL injection. You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
Also, as stated in the introduction to the PHP manual chapter on the mysql_* functions:
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
You appear to be using either a DATETIME or TIMESTAMP column for holding a date value; I recommend you consider using MySQL's DATE type instead. As explained in The DATE, DATETIME, and TIMESTAMP Types:
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
You should consider creating a timestamp from that date witk mktime()
eg:
$date = explode('/', $_POST['date']);
$time = mktime(0,0,0,$date[0],$date[1],$date[2]);
$mysqldate = date( 'Y-m-d H:i:s', $time );
$date_field = date('Y-m-d',strtotime($_POST['date_field']));
$sql = mysql_query("INSERT INTO user_date (column_name,column_name,column_name) VALUES('',$name,$date_field)") or die (mysql_error());
You must make sure that the date format is YYYY-MM-DD on your jQuery output. I can see jQuery returns MM-DD-YYYY, which is not the valid MySQL date format and this is why it returns an error.
To convert it to the right one you could do this:
$dateFormated = split('/', $date);
$date = $dateFormated[2].'-'.$dateFormated[0].'-'.$dateFormated[1];
Then you will get formatted date that will be valid MySQL format, which is YYYY-MM-DD, i.e. 2012-08-25
I would also recommend using mysql_real_escape_string as you insert data into database to prevent SQL injections as a quick solution or better use PDO or MySQLi.
Your insert query using mysql_real_escape_string should rather look like this:
$sql = mysql_query( "INSERT INTO user_date VALUE( '', '" .mysql_real_escape_string($name). "', '" .mysql_real_escape_string($date). "'" ) or die ( mysql_error() );
Get a date object from the jquery date picker using
var myDate = $('element').datepicker('getDate')
For mysql the date needs to be in the proper format. One option which handles any timezone issues is to use moment.js
moment(myDate).format('YYYY-MM-DD HH:mm:ss')
The simplest method is
$dateArray = explode('/', $_POST['date']);
$date = $dateArray[2].'-'.$dateArray[0].'-'.$dateArray[1];
$sql = mysql_query("INSERT INTO user_date (column,column,column) VALUES('',$name,$date)") or die (mysql_error());
HTML:
<div class="form-group">
<label for="pt_date" class="col-2 col-form-label">Date</label>
<input class="form-control" type="date" value=<?php echo date("Y-m-d") ;?> id="pt_date" name="pt_date">
</div>
SQL
$pt_date = $_POST['pt_date'];
$sql = "INSERT INTO `table` ( `pt_date`) VALUES ( '$pt_date')";
Suppose you receive a Christmas date:
December 25, 2021 (25 de Diciembre del año 2021) in string format: "d-m-Y" for example "12-25-2021". First create a valid DateTime object from the received format:
var_dump(DateTime::createFromFormat("d-m-Y","25-12-2021", new DateTimeZone("America/Argentina/Buenos_Aires")));
This generates as output:
object(DateTime)#2 (3) {
["date"]=>
string(26) "2021-12-25 10:21:11.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(30) "America/Argentina/Buenos_Aires"
}
Now to get the date field from the DateTime object ready to go using format("Y-m-d H:i:s")):
var_dump(DateTime::createFromFormat("d-m-Y","25-12-2021",new DateTimeZone("America/Argentina/Buenos_Aires"))->format("Y-m-d H:i:s"));
This generates as output a ready to insert value:
string(19) "2021-12-25 10:56:30"
In summary now you can insert a formated date ('DD-MM-YYYY') in MySQL like this:
<?php
//string input post like "25-12-2021"
$date_input = $_POST['date_input'];
//create DateTime object
$date_time_obj=DateTime::createFromFormat("d-m-Y","25-12-2021",new DateTimeZone("America/Argentina/Buenos_Aires"));
//format date ready to insert as string at MySQL
$str_date=$date_time_obj->format("Y-m-d H:i:s");
?>
Now run directly from PHP to MySQL as a query:
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
//verify connection
if (mysqli_connect_errno()) {
printf("Error de conexión: %s\n", mysqli_connect_error());
exit();
}
//prepare the query to execute
$stmt = $mysqli->prepare("INSERT INTO table_example (DATE_FIELD) VALUES (?)");
//prevent sql injection
$stmt->bind_param('s', $str_date);
//execute prepared statements
$stmt->execute ();
?>
These days, I am not good with dates. Thanks to the following work, I can print the dates in the format I want.
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$scr = strtotime($year . '-' . $month . '-' . $day);
$gelis_tarihi = date('Y-m-d', $scr);
$yil = $_POST['yil'];
$ay = $_POST['ay'];
$gun = $_POST['gun'];
$birlestir = strtotime($yil . '-' . $ay . '-' . $gun);
$gelis_tarihi = date('Y-m-d', $birlestir);
Try Something like this..
echo "The time is " . date("2:50:20");
$d=strtotime("3.00pm july 28 2014");
echo "Created date is " . date("d-m-y h:i:sa",$d);
First of all store $date=$_POST['your date field name'];
insert into **Your_Table Name** values('$date',**other fields**);
You must contain date in single cote (' ')
I hope it is helps.
In my UI the dates are shown like this - dd.mm.YYYY hh:ii:ss. The users are able to edit/add new dates and most probably they'll try to use the same format (24.06.2012 15:35:00) which can not be used for a SQL query. Here is what I've done till now:
$dt = (date_parse_from_format("d.m.Y H:i:s", $data['event_time']));
$newdate = sprintf("%02d-%02d-%04d %02d:%02d:%02d" , $dt['day'], $dt['month'], $dt['year'], $dt['hour'], $dt['minute'], $dt['second']);
$test = date("Y-m-d H:i:s", strtotime($newdate));
if ($test == "1970-01-01 01:00:00")
{
throw new Exception('Invalid date');
}
What happens is - if I leave the check if ($test == "1970-01-01 01:00:00") I get an exception, but if I comment the $test = date("Y-m-d H:i:s", strtotime($newdate)); line and the check the date is inserted only with zeros.
$newdate is a sting in the right format for SQL - YYYY-mm-dd H:i:s but obv. I miss something here. How to insert this string as a valid SQL datetime?
Thanks
Leron
The DateTime class was introduced in PHP 5.2 and would allow you to use something like this
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time']);
if($dt === false){
throw new Exception("Invalid date");
}
DateTime::createFromFormat returns false on failure (This method is only available since PHP 5.3)
Then when saving to the database you can use the following to get the correct format for MySQL
$dt->format("Y-m-d H:i:s")
MySQL provides the FROM_UNIXTIME( ) and UNIX_TIMESTAMP( ) functions to convert a Unix timestamp to a MySQL date format, and vice versa.
$SqlString = "INSERT INTO table(mydate, content) VALUES (FROM_UNIXTIME($mydate), $content)";
UNIX_TIMESTAMP, if called with no argument, returns a Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC. date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the
format YYMMDD or YYYYMMDD.
$SqlString = "SELECT *, UNIX_TIMESTAMP($mydate) AS mydate FROM table WHERE conId = $conId";
Take a deeper look at these MySql functions and also the mktime() function could help you.
I have a PHP/MySQL date formatting problem. Here, i create the date variables:
$checkDate = date("d/m/y H:i", time());
$datestrto = strtotime($checkDate);
Then i insert it to a mysql table with the column Datatype of bigint.
When i then, later on, when i need to echo the date, i use this code:
echo '<td>'.date("d/m/y H:i",$row['f_uploaded_date']).'</td>';
But istead of echo'ing the date in the format D/M/Y H:i, it echo'es the date in the format of m/d/y H:i.
Can anyone explain why this is happening, and how to fix it?
Thank you in advance,
Adam
When you insert it into the MySQL table do it like this:
INSERT INTO yourtable(something,somedate) VALUES('something',str_to_date('".$checkDate."','%d/%m/%y %H:%i'))
and when you pull it out from MySQL then do it like this:
SELECT *,date_format(somedate,'%D/%M/%Y %H:%i') as formateddate from yourtable
then in php you use:
$row['formateddate']
Hope it helps you :)
EDIT:
The complete code:
$ddate = date("d/m/y H:i", time());
$sql = "INSERT INTO files (rowID, file, mimetype, data, uploaded_by, uploaded_date, size, times_downloaded, description) VALUES (NULL, '$fileName', '$fileType', '$content', '$user', str_to_date('".$ddate."','%d/%m/%y %H:%i'), $fileSize, 0, '$description')";
So you convert a unix timestamp into a formatted date string then convert the formatted time string back into a unix timstamp and insert that into your database. Wouldn't it just be simpler to just insert the unix timestamp you got in the first place? Or not even bother with PHP code and
INSERT INTO sometable (id, f_uploaded_date)
VALUES ($id, UNIX_TIMESTAMP(NOW()))
?
I suspect the explicit problem you describe is due to the fact that strtotime expects date strings of format 99/99/9999 to be the american style of mm/dd/yyyy rather than dd/mm/yyyy as used in the UK.
First,
$checkDate = date("d/m/y H:i", time());
$datestrto = strtotime($checkDate);
is quite funny way of assigning time() frunction result to $datestrto variable.
Next, you don't need that variable either, as you just can use unix_timestamp() mysql function in the insert query.
Now to your question.
istead of echo'ing the date in the format D/M/Y H:i, it echo'es the date in the format of m/d/y H:i.
double-check your syntax. there is a typo somewhere.
You can pull a date format from your mysql database and then when converting to a php variable you can use:
$num=mysql_numrows($result);
$i=0;
while ($i <= $num) {
$date=mysql_result($result,$i,"Date");
$date = date('d-m-Y', strtotime($date));
echo $date."<br>";
}
Where $result is your mysql query result and "Date" is the name of the column. However I am unsure of using this method with the time.
--EDIT--
link: http://php.net/manual/en/function.date.php