I am writing a query in php using a string sent from a android java application.
The query is something like :
$insertSQL = sprintf("INSERT INTO app_DuckTag (taste) VALUES (%s) WHERE species=%s AND timestamp=%s",
GetSQLValueString($_POST['taste'], "text"),
GetSQLValueString($_POST['species'], "text"),
GetSQLValueString($_POST['timestamp'], "text"));
But I doubt timestamp is stored as a string inside MySQL.
How should I convert the string to time format as in MySQL?
The strtotime(string) php function converts it to unix time.
But the MySQL stores it differently, I guess. Thank you.
EDIT: This is how it shows up in MySQL phpmyadmin: 2011-08-16 17:10:45
EDIT: My query is wrong though. Cannon use a where clause with Insert into.
The query has to be UPDATE .... SET ... = ... WHERE ....
But the accepted answer is the correct way to use the time inside the WHERE clause.
This should be all:
date("Y-m-d H:i:s", strtotime($_POST['timestamp']));
if you want to check for timezones and such you should use strftime instead of date
If you can get the input 'string' (which you haven't provided the format that you're receiving it in) to a Unix timestamp value, you can easily convert it to a MySQL datetime format like this:
$mysqldatetime = date("Y-m-d H:i:s", $unixTimeStampValue);
This will produce a string similar to the following:
2011-08-18 16:31:32
Which is the format of the MySQL datetime format. If you are using a different time format, then the first argument to the date function will be different.
See the manual for the date function for more information and other ways you can format the value that it returns.
Edit
You are receiving a string formatted in MySQL datetime format. After sanitizing it, you can insert it directly into the database. To MySQL it may be a 'datetime' data type, but to PHP it is simply a string (just like your entire SQL query is nothing more than a string to PHP).
$timestamp = mysql_real_escape_string($_POST['timestamp']);
You should be able to safely insert that into your database for the timestamp field.
There is a function FROM_UNIXTIME in mysql. Why don't you want to use it?
Related
Let's say I have this date, e.g.:
12-DEC-14 11.55.51.000000000 AM
and then I assigned it to variable, let's say:
$date = '12-DEC-14 11.55.51.000000000 AM';
Now the question is, how do I add 1 month or 2 months or so to that $date using only
php, without using any oracle sql date functions, just pure php,
because I will save the result to oracle db table in that same format.
The result should be like, e.g.:
$nextmonth = '12-JAN-15 11.55.51000000000 AM';
Then that's the time I can save that $nextmonth in the table column. So how ?
You can use DateTime classes in this case, load that date and define its format. Then after creating the datetime object, adjust it to your x number of months, then present it again with the original format.
$input = '12-DEC-14 11.55.51.000000000 AM';
$date = DateTime::createFromFormat('d-M-y h.i.s A', $input);
$next_month = clone $date;
$next_month->modify('+1 month');
echo strtoupper($next_month->format('d-M-y h.i.s A'));
This is probably only a very long comment rather than a real answer, but some of your comments let me think we have an instance of XY problem here:
it's a TIMESTAMP(6) , but the format is exactly like this inside that column 12-DEC-14 11.55.51.000000000 AM
how bout the succeeding 9 zeroes ?, won't that cause any errors in oracle if I just append it like e.g echo strtoupper($next_month->format('d-M-y h.i.s.000000000 A'));
A TIMESTAMP(6) store a date-time information (a "point in time"). It hasn't any "format" par se. TIMESTAMP are great data type, as they allow you to easily perform calculation on data and time with a great precision at DB level such as "adding one month".
But, without explicit request from your part, a default format is used to convert timestamps from and to strings.
Maybe your real issue is that Oracle try to implicitly convert your string to timestamp using its standard format. Usually, it is a far better idea to explicitly convert data type yourself. From the documentation:
Oracle recommends that you specify explicit conversions, rather than rely on implicit or automatic conversions, for these reasons:
[...]
implicit conversion depends on the context in which it occurs and may not work the same way in every case. For example, implicit conversion from a datetime value to a VARCHAR2 value may return an unexpected year depending on the value of the NLS_DATE_FORMAT parameter.
Please note that above statement is true for TIMESTAMP too, as the "standard" format is user-definable using NLS_TIMESTAMP_FORMAT.
The PHP documentation has a similar warning:
DATE columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT command.
As a personal suggestion, I would say that you should never rely on implicit date/timestamp conversion, as any change of the relevant configuration settings at DB-level or for the current session will break your code.
So, depending the way you insert your value, using an explicit format might be as simple as wrapping the bind variable in a proper TO_TIMESTAMP(....) call:
// query the original data
$q = oci_parse ($connection ,
"INSERT INTO ....
VALUES (TO_TIMESTAMP(:date_as_str, 'YYYY-MM-DD HH:MI:SS.FF'), other_columns...)");
$q = oci_parse ($connection ,
"INSERT INTO ....
VALUES (TO_TIMESTAMP(:date_as_str, 'YYYY-MM-DD HH:MI:SS.FF'), other_columns...)");
Coming back to your initial question: "how to add one month in a raw date" " I will save the result to oracle db table in that same format data type" , this should be as simple as adding 1 month when inserting the value:
$q = oci_parse ($connection ,
"INSERT INTO ....
VALUES (TO_TIMESTAMP(:date_as_str, 'YYYY-MM-DD HH:MI:SS.FF')
+ INTERVAL '1' MONTH, other_columns...)");
Hello I'd doing a project which is related to android , php and mysql, there is this function that i need to get the user input from android device, and post it to php script which then query the database, one of the inputs is a time string the format is "XX:XX:XX" , this string will be stored as a time in mysql, my question is how do I convert the string into mysql time format in php ? (only time, NO DATE)
according to http://dev.mysql.com/doc/refman/5.0/en/time.html, the TIME type should accept strings formatted like 'HH:MM:SS' so you should be able to directly save your data without the need to convert anything.
Unix time or full date format ?
for unix time do :
<?php
$time=strtotime($input);
?>
and full-date format :
<?php
$time=date('c',strtotime($input));
?>
any else ?, good luck
To convert the date in a mysql Timestamp format you can use the following snippet :
$mysqlTime = date("H:i:s", strtotime("20:30:10"));
the variable $mysqlTime will hold it for you.
I think I clearly understood your question.
I am trying to insert a date in my Database which I get from a php input.
The code I am using to insert the value looks like this
$length = strrpos($fristdatum, " ");
$newDate = explode(".", substr($fristdatum, $length));
$fristdatum = $newDate[2] . "-" . $newDate[1] . "-" . $newDate[0];
Lets say I enter 14.12.2012 as the date if I echo $fristdatum I get 2012-12-14 but as soon as I insert it in my MySQL DB it turn to 2014.12.20 any ideas?
The Column Type is date. The insert is somewhat like this
mysql_query("INSERT INTO sch_anschreiben (date)values('$fristdatum'))
there are more values but I guess that doesn't matter
Thanks in Advance!
Well thanks for the help guys i figured it out i used $fristdatum in a array for str_replace ,after i formated it, like this
$patern = array("[Date]")
$words=array($fristdatum)
$content = str_replace($patern, $words, $content);
and after that inserted it in the DB now I changed it so it would format after the str_replace and it seems to work just fine.
also would appreciate if someone could explain me why^^.
Instead of explode and hard coded conversion, prefere using DateTime::createFromFormat if you have PHP 5.3 or later.
$date = DateTime::createFromFormat('d. m. Y',$fristdatum);
echo $date->format('Y-m-d');//echoes 2012-12-14
Now that you correct your script to register your dates the right way, you should ensure your database is good.
You can use this request I think :
UPDATE yourtable SET yourdate=CONCAT(MONTH(yourdate),'-',DAY(yourdate),'-',YEAR(yourdate)) WHERE MONTH(yourdate) > 12
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.
So if you want to store it like 14-12-2012 then use its datatype as varchar.
Convert it into Y-M-D format. You should directly put 2012-12-14 onto your database.
Hi i'm using php5 and mysql.
I have a time like that 10:00, 10:45 ... and i shoult put it a mysql database in form 'hh:mm:ss'
I tryed in different way but nothing works.
What i try was:
$time= time('H:i:s', $mytime)
$time= time('H:i:s', strtotime($mytime))
$time= strtotime($mytime)
$time= strtotime($mytime.':00')
$sql = "INSERT INTO table SET `time`='$mytime';
Hint: be sure you are using proper Mysql field format
Another hint: do not use randomly picked PHP functions. At least try to read the function description in the manual. It can give you idea if this function suit your needs or not.
strtotime need a complete date as input and outputs an int. You don't need an int for mysql, you only need the string you have plus the seconds info:
$time = $mytime.':00';
Then insert time in db, as #Your_Common_Sense says, you need to user TIME datatype in order to insert a time in this format.
I have thousands of dates in the following format:
2011-10-02T23:25:42Z (aka ISO 8601 in UTC)
What MySQL data type should I use for storing such a ISO8601 date in a MySQL database? E.g. Datetime, timestamp or something else?
Which is best for comparison (eg. getting records between two dates/times) and ordering the results from queries? What about if the database is very large?
And what would be the best way to convert the above PHP string for MySQL storage? (I'm guessing date_default_timezone_set('UTC'); would be used?)
I think that keeping your date-time values in field of type DATETIME would be kind of natural way.
From my own experience with my current PHP application, only read / write operations concerning this information may be problematic.
One of possible solutions (assuming that you use DATETIME data type) for properly performing the whole process could be the following approach:
Reading DATETIME values for PHP use
Acquire DATETIME fields from your database converting them in the query to string representation in the form of '2011-10-02T23:25:42Z' by using DATE_FORMAT MySQL function with '%Y-%m-%dT%H:%i:%sZ' formatting string (docs on DATE_FORMAT)
Read fetched column value in this specific format and convert it in PHP from string to real date-time representation valid for PHP (such as DateTime class objects and DateTime::createFromFormat static method given 'Y-m-d\TH:i:s\Z' formatting string (T and Z are escaped to avoid treating them as formatting directives) (docs for the method).
Use converted values as real date-time values with all the logic applicable, like real date comparisons (not text-comparisons), etc.
Writing PHP date-time to MySQL database
Convert i.e. PHP DateTime class object to our ISO 8601 in UTC format string representation using DateTime class object's format method with the same as before 'Y-m-d\TH:i:s\Z' formatting string (documentation).
Perform INSERT / UPDATE operation on database information using such prepared string as a parameter for MySQL function STR_TO_DATE (with '%Y-%m-%dT%H:%i:%sZ' formatting string) which converts it to real database DATETIME value (docs on STR_TO_DATE).
Example code in PHP
Below please find a draft example of such approach using PDO objects:
$db = new PDO('mysql:host=localhost;dbname=my_db;charset=utf8', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
// run the query aquring 1 example row with DATETIME data
// converted with MySQL DATE_FORMAT function to its string representation
// in the chosen format (in our case: ISO 8601 / UTC)
$stmt = $db->query("SELECT DATE_FORMAT(dt_column, '%Y-%m-%dT%H:%i:%sZ') AS formatted_dt_col"
." FROM your_table LIMIT 1");
if($stmt !== FALSE) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// convert the acquired string representation from DB
// (i.e. '2011-10-02T23:25:42Z' )
// to PHP DateTime object which has all the logic of date-time manipulation:
$dateTimeObject = DateTime::createFromFormat('Y-m-d\TH:i:s\Z', $row['formatted_dt_col']);
// the following should print i.e. 2011-10-02T23:25:42Z
echo $dateTimeObject->format('Y-m-d\TH:i:s\Z');
// now let's write PHP DateTime class object '$dateTimeObject'
// back to the database
$stmtInsertDT = $db->prepare("INSERT INTO your_table(dt_column) "
. " VALUES ( STR_TO_DATE(:par_formatted_dt_column, '%Y-%m-%dT%H:%i:%sZ') )");
$dtAsTextForInsert = $dateTimeObject->format('Y-m-d\TH:i:s\Z');
// convert '$dateTimeObject' to its ISO 8601 / UTC text represantation
// in order to be able to put in in the query using PDO text parameter
$stmtInsertDT->bindParam(':par_formatted_dt_column', $dtAsTextForInsert, PDO::PARAM_STR);
$stmtInsertDT->execute();
// So the real insert query being perform would be i.e.:
/*
INSERT INTO your_table(dt_column)
VALUES ( STR_TO_DATE('2011-10-02T23:25:42Z', '%Y-%m-%dT%H:%i:%sZ') )
*/
}
}
catch(\PDOException $pexc) {
// serve PDOException
}
catch(\Exception $exc) {
// in case of no-PDOException, serve general exception
}
This approach helped me a lot in operating date-time values between PHP and MySQL database.
I hope it might occur helpful for you also.
You can use DateTime data type for storing the date and time.
Use CAST function to cast such strings into mysql DateTime type.
Here is an example:
CAST("2011-10-02T23:25:42Z" AS DATETIME)
This will give you 2011-10-02 23:25:42.
Hope this will help you.
You can easily convert the date using strtotime function of php :
date_default_timezone_set('UTC');
$date = '2011-10-02T23:25:42Z';//(aka ISO 8601 in UTC)
$time = strtotime($date); //time is now equals to the timestamp
$converted = date('l, F jS Y \a\t g:ia', $time); //convert to date if you prefer, credit to Marc B for the parameters
Now you would simply insert your date in MySQL using timestamp or datetime depending on which one fit the most your needs. Here the most important things you should know about both types.
Timestamp
Range of '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC
Affected by the time-zone setting.
4 bytes storage
allow on update current_timestamp on columns for all versions.
Index is way faster
NULL is not a possible default value
Values are converted from the current time zone to UTC for storage, and converted back from UTC to the current time-zone for retrieval.
Datetime
Range of '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
Constant (time-zone won't affect)
8 bytes storage
allow update on columns only as of version 5.6.5
Which is best for comparison (eg. getting records between two
dates/times) and ordering the results from queries? What about if the
database is very large?
According to the previous points I stated, then you should use timestamp for a very large database as the storage is smaller, and the index faster which will give you better performance for comparison. However, you MUST MAKE SURE your date will fit the limits of the timestamp I previously mentioned, else you have no choice and must use datetime.
Documentation for strtotime : http://php.net/manual/en/function.strtotime.php
And please, for the sake of SO's answerer who keep repeating every day to not use the mysql* DEPRECATED functions, please use PDO or mysqli* when you will do your inserts.
http://php.net/manual/en/book.pdo.php
http://php.net/manual/en/book.mysqli.php
You can not store date in raw UTC ISO8601 format (with 2011-10-02T23:25:42Z representation) and save all SQL DATETIME functionality.
But you should know, that MySQL ( regarding to http://dev.mysql.com/doc/refman/5.5/en/datetime.html ) always store time/date in UTC.
Also you can modify timezone for your connection
http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
So, if you execute in PHP
date_default_timezone_set('UTC');
and in MySQL
SET time_zone = +00:00
sure PHP and MySQL would use UTC.
After that you can convert all database strings to DateTime without caring about timezone mismatch.
To convert any PHP DateTime (without carrying about its internal timezone) to MySQL datetime string you should set DateTime object timezone to UTC.
$datetime->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s');
Using your datetime on my system which is PDT:
SELECT CONVERT_TZ(str_to_date('2011-10-02T23:25:42Z','%Y-%m-%dT%H:%i:%sZ'),'+00:00','SYSTEM') from dual;
2011-10-02 16:25:42
If your datetime has a fractional microsecond; include the .%f before the Z as follows:
SELECT CONVERT_TZ(str_to_date('2011-10-02T23:25:42.123456Z','%Y-%m-%dT%H:%i:%s.%fZ'),'+00:00','SYSTEM') from dual;
2011-10-02 16:25:42.123456
Here are the points why it is better to use datetime.
With datetime you will be able to do date manipulations on mysql side - such as subtracting day,month
You will be able to sort data.
If DB is huge - varchar takes more place on HDD