pgSQL : insert date format (leading zeros)? - php

I want to insert a date into my pg database, but I haven't got a clue what the correct format is and the pg help isn't really helping.
I have my date from form in d-m-yyyy format. So leading zeros are omitted.
How can I insert this correctly, is there a function to add leading zeros (either pg or php) ?

Check to_date(text, text) function (Table 9-21 contains all supported patterns):
SELECT to_date('1-9-2011', 'DD-MM-YYYY');
to_date
------------
2011-09-01
(1 row)
As you see leading zeros are properly added in output date.

INSERT INTO TheTable (the_date) VALUES ('yyyy-mm-dd')
is the correct order in SQL
$psql_str = date('yyyy-mm-dd', date_parse_from_format('d-m-yyyy', $date_str));
converts your $date_str to the expcted format.

The best thing to do is insert the date in an unambiguous format, since that's guaranteed to always work, regardless of any settings that the server may have. The recommended format is YYYY-MM-DD. You can change your date to that format with this function:
function convertDate($old) {
$date = explode('-', $old);
if (strlen($date[0]) == 1)
$date[0] = '0' . $date[0];
if (strlen($date[1]) == 1)
$date[1] = '0' . $date[1];
$new = date[2] . '-' . $date[1] . '-' . $date[0];
return $new;
}
Other data formats are also possible, but they are less recommended, since they rely on settings that may vary from one server to another. For more information, check out the relevant section of the documentation.

Actually, if you verify that DateStyle is set to DMY (or, better, "ISO,DMY"), then you don't have to do anything:
postgres=# create table test_table (date_field date);
CREATE TABLE
postgres=# show DateStyle;
DateStyle
-----------
ISO, MDY
(1 row)
postgres=# set DateStyle='ISO, DMY';
SET
postgres=# insert into test_table (date_field) values ('2-4-2011');
INSERT 0 1
postgres=# select * from test_table;
date_field
------------
2011-04-02
(1 row)

Related

Insert Query for time Php

My PHP string contain this data :
$OpenDate = '20-Sep-18' ;
but when i insert it into database it give me an error :
Column not found: 1054 Unknown column 'Sep' in 'field list'' in C:\xampp
tried to replace all ' - ' to ' _ ' but it has not worked also .
EDIT :
QUERY CODE :
$stmt = $conn->query("INSERT INTO `ticketinfo`
(`tOrderId`)
VALUES
( ".$tOrderID.") on duplicate key update `tPLU`= ".$tPLU." , `tPrice`= ".$Total1." , `tBuy`=".$OpenDate );
the problem is in the $OpenDate
MySQL datetime format is 'YYYY-MM-DD HH:MM:SS'. For date alone, it will be: 'YYYY-MM-DD'
In PHP (Application code), you will need to convert your date string to an acceptable format for MySQL. You can use strotime() function to convert your date string to a Timestamp. Then, use date() function to convert into YYYY-MM-DD.
Eventually, use this converted date string in your Insert query.
Also, based on your error message, your query parameters need escaping. Please learn and implement Prepared Statements
Try (Rextester Demo):
$OpenDate = '20-Sep-18';
$mySQLFormatOpenDate = date('Y-m-d', strtotime($OpenDate));
echo $mySQLFormatOpenDate; // test display the formatted date
/* Now use $mySQLFormatOpenDate in your SQL Insert query */
Additional Details for format options used:
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
m Numeric representation of a month, with leading zeros 01 through 12
d Day of the month, 2 digits with leading zeros 01 to 31
According to https://dev.mysql.com/doc/refman/8.0/en/datetime.html the proper date format is YYYY-MM-DD, so no months in letters but in numbers. Should be 2018-09-20.

PHP: Inserting date as string turns to -2008

When I MySqlI Query to add a session info, I add the date as a string but when I look in phpMyAdmin the date is -2008. I echo out the date string and it is the correct date. Connection to the database is fine
PHP:
$endDate = date('d-m-Y',strtotime("+30 days"));
$sresult = mysqli_query($con, "INSERT INTO `sessions`(`session_id`, `session_token`, `session_serial`, `session_date`) VALUES (".rand(120, 1200).",3564578,1234586723, ".$endDate.")") or die("Failed to query database ".mysqli_error($con));
echo "Login success!!! Welcome ".$row['uid']."".$endDate; #Correct Date
phpMyAdmin:
session_id,
session_token,
session_serial,
session_date,
161,
3564578,
1234586723,
-2008,
Should Be:
session_id,
session_token,
session_serial,
session_date,
161,
3564578,
1234586723,
19-09-2018
You're not escaping the date value, and it seems like the field type for session_date in the database is an integer.
Since you're not escaping the value when generating the SQL, it's parsed as 19 - 09 - 2018, which depending on which month and day you run this, ends up being -2008 (nineteen minus nine minus two thousand and eighteen).
The first fix is to properly enclose the value (you should be using prepared statements for this as that would handle it automatically for you, but since you can trust the data):
... 1234586723, '" . $endDate . "')
Be aware that MySQL probably expects the date in the YYYY-mm-dd ISO format for date fields, so you probably want to change your generated date string to that as well.

strtotime not inserting into database

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

between operator for timestamps in mysql query

I have a form to pick up dates from calender. That form will pass start date and end date. My database table stores date in time-stamp format. I have to create a query to pick records from database table between start date and end date. How can I make a query? I have tried the code below, but which is not working.
if(isset($_POST['filter']))
{
$sid=$_POST['sid'];
$start= date("dMY",strtotime($_POST['start']));
$end= date("dMY",strtotime($_POST['end']));
$res=$db->fetchAll("SELECT * FROM `logfile` WHERE `site_id`=".$sid." AND (date('dMY',`timestamp`) BETWEEN $start AND $end)");
}
Any thoughts?
Thanks.
You're forcing PHP and MySQL to do a lot of useless date/time string<->native conversions for no reason.
Why not simply have:
$start = strtotime($_POST['start']);
SELECT ... WHERE `timestamp` BETWEEN FROM_UNIXTIME($start) AND ...
if $_POST['start'] and $_POST['end'] are already in timestamp format, just don't change them. In other case just convert the string in timestamp:
$start = strtotime($_POST['start']); // where $_POST['start'] might be 2012/08/07
$end = strtotime($_POST['end']);
$res=$db->fetchAll("SELECT * FROM logfile WHERE site_id=".$sid." AND date BETWEEN $start AND $end");
As #Matei Mihai said you don't need to convert $_POST['start'] and $_POST['end'] to timestamp format and you must enclose date columns in quotes.
Also you need to convert date in MySQL compatible format like '2012-08-01'.
"SELECT *
FROM `logfile`
WHERE `site_id`=".$sid." AND
(date('dMY',`timestamp`) BETWEEN '$start' AND '$end')");

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