Insert Query for time Php - 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.

Related

how could i get date from varchar column in mysql

I want to get date from VARCHAR column.
(eg: 4/14/2018 12:00:00 AM)
How do I display only date
(eg: 4/14/2018)?
SELECT date(created_at) from self_balance
here created_at(varchar)
this returns NULL value
You can run this query to get your output,
SELECT DATE_FORMAT(STR_TO_DATE(created_at, "%Y-%m-%d"), "%Y-%m-%d") FROM
self_balance
First I am matching date format and converting it to date and then formatting.
You can fetch date like a normal string from the database then you need to use strtotime which parses an English textual DateTime into a Unix timestamp. Then you can use
date function which returns the formatted date string. I have passed a static string. You can pass your string variable which you are fetching from the database
$time = strtotime($date_string_from_database);
<?php
$time = strtotime('4/14/2018 12:00:00 AM');
$newformat = date('m/d/Y',$time);
echo $newformat;
?>
You can see the live demo here

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.

PHPExcel Date Format

I am getting an output from MS SQL server in the '2012-08-09 00:00:00' (without quotes) format.
However, when I write it to excel file I'm unable to write it in date format to have dd mmm yyyy formatting on excel.
As a result i tried to write in format =date(2012,08,09) as a formula to the respective cells.
But I don't want to output it as a formula but rather the value '09 Aug 2012' with the data type integrity intact. How do I do this? Or is there a simpler method?
I read through the documentation but it was not clear to me, thought I would ask for clarification.
Regards.
Sorry for not being detailed enough.
I am using the PHPExcel library.
From my sql array, i use the following:
$t_year = substr($xls_column_datas["colname"],0,4);
$t_month = substr($xls_column_datas["colname"],5,2);
$t_day = substr($xls_column_datas["colname"],8,2);
$t_format = $t_year . "," . $t_month . "," . $t_day ;
$t_format = '=date('.$t_format.')';
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($data_column_num, $data_row_num, $t_format );
$objPHPExcel->getActiveSheet()->getStyleByColumnAndRow($data_column_num, $data_row_num)->getNumberFormat()->setFormatCode('[$-C09]d mmm yyyy;#');
in my excel output, it shows column A2 for e.g. =DATE(2012,8,9)
rather than showing up as a formula I want excel to recognize '2012-08-09 00:00:00' is a date time and format it to dd mmm yyyy.
Is this getting clear? Sorry.
Is your problem in getting the date from MS SQL as a date/time, or setting the Excel date?
There is a whole section of the PHPExcel documentation that explains the use of the PHPExcel_Shared_Date::PHPToExcel($PHPDate) and PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day, $hours=0, $minutes=0, $seconds=0) helper methods for converting PHP dates to an Excel datetime stamp value that you set as the cell value, and then you apply a number format mask of one of the date masks such as PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2 to that cell
Instead of
$t_year = substr($xls_column_datas["colname"],0,4);
$t_month = substr($xls_column_datas["colname"],5,2);
$t_day = substr($xls_column_datas["colname"],8,2);
$t_format = '=date('.$t_format.')';
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($data_column_num, $data_row_num, $t_format );
$objPHPExcel->getActiveSheet()->getStyleByColumnAndRow($data_column_num, $data_row_num)->getNumberFormat()->setFormatCode('[$-C09]d mmm yyyy;#');
try setting
$t_year = substr($xls_column_datas["colname"],0,4);
$t_month = substr($xls_column_datas["colname"],4,2); // Fixed problems with offsets
$t_day = substr($xls_column_datas["colname"],6,2);
$t_date = PHPExcel_Shared_Date::FormattedPHPToExcel($t_year, $t_month, $t_day);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(
$data_column_num, $data_row_num, $t_date
);
$objPHPExcel->getActiveSheet()
->getStyleByColumnAndRow($data_column_num, $data_row_num)
->getNumberFormat()->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14
);
$date = PHPExcel_Style_NumberFormat::toFormattedString($data, "M/D/YYYY");
Though it is unclear what are asking, If you are looking for a date conversion
// convert old date string to YYYYmmdd format
$date = date('d M Y', strtotime($old_date));
this will output date in 09 Aug 2012 format
Why not let the server to the formatting for you? Use this query to format the date
SELECT convert(varchar(15), getdate(), 106)
This will result 11 Sep 2012
SQL SERVER: Date Format

pgSQL : insert date format (leading zeros)?

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)

Optional month or day in MySQL date field from PHP

I have a problem where I need to handle dates where the month and day parts are optional. For example, the year will always be known but sometimes the day or month and day will be unknown.
In MySQL I can create a table with a date field and while I can't find any reference in the MySQL Manual it will accept the following as valid:
(YYYY-MM-DD format):
2011-02-10 // Current date
2011-02-00 // Day unknown so replaced with 00
2011-00-00 // Day and month unkown so replaced with 00-00
Test calculations from within the database work fine so I can still sort results easily. In the manual it says that month needs to be between 01 and 12, and day between 01 and 31 - but it does accept 00.
First question: Am I going to run into trouble using 00 in the month or day parts or is this perfectly acceptable?
Next question: Is there a PHP function (or MySQL format command) that will automatically format the following dates into the required format string?
2011 becomes 2011-00-00
2011-02 becomes 2011-02-00
Or do I need write a special function to handle this?
The following doesn't work:
<?php
$date = date_create_from_format('Y-m-d', '2011-00-00');
echo date_format($date, 'Y-m-d');
// Returns 2010-11-30
$date = date_create_from_format('Y-m-d', '2011-02-00');
echo date_format($date, 'Y-m-d');
// Returns 2011-01-31
?>
Third question: Is there a PHP function (or MySQL command) to format the dates for use in PHP?
Finally, is this the best approach? Or is there a 'best practise' method?
EDIT:
Here is what I'm currently doing:
A date field can accept a date in the format YYYY, YYYY-MM, or YYYY-MM-DD and before sending to the database it is processed in this function:
/**
* Takes a date string in the form:
* YYYY or
* YYYY-MM or
* YYYY-MM-DD
* and validates it
*
* Use date_format($date, $format); to reverse.
*
* #param string $phpDate Date format [YYYY | YYYY-MM | YYYY-MM-DD]
*
* #return array 'date' as YYYY-MM-DD, 'format' as ['Y' | 'Y-m' | 'Y-m-d'] or returns false if invalid
*/
function date_php2mysql($phpDate) {
$dateArr = false;
// Pattern match
if (preg_match('%^(?P<year>\d{4})[- _/.]?(?P<month>\d{0,2})[- _/.]?(?P<day>\d{0,2})%im', trim($phpDate), $parts)) {
if (empty($parts['month'])) {
// Only year valid
$date = $parts['year']."-01-01";
$format = "Y";
} elseif (empty($parts['day'])) {
// Year and month valid
$date = $parts['year']."-".$parts['month']."-01";
$format = "Y-m";
} else {
// Year month and day valid
$date = $parts['year']."-".$parts['month']."-".$parts['day'];
$format = "Y-m-d";
}
// Double check that it is a valid date
if (strtotime($date)) {
// Valid date and format
$dateArr = array('date' => $date, 'format' => $format);
}
} else {
// Didn't match
// Maybe it is still a valid date
if (($timestamp = strtotime($phpDate)) !== false) {
$dateArr = array('date' => date('Y-m-d', $timestamp), 'format' => "Y-m-d");
}
}
// Return result
return $dateArr;
}
So it pattern matches the input $phpDate where it must begin with 4 digits, then optionally pairs of digits for the month and the day. These are stored in an array called $parts.
It then checks if months or days exist, specifying the format string and creating the date.
Finally, if everything checks out, it returns a valid date as well as a format string. Otherwise it returns FALSE.
I end up with a valid date format for my database and I have a way of using it again when it comes back out.
Anyone think of a better way to do this?
I have a problem where I need to handle dates where the month and day parts are optional.
For example, the year will always be known but sometimes the day or month and day will be
unknown.
In many occasions, we do need such 'more or less precise' dates, and I use such dates as 2011-04-01 (precise), as well as 2011-04 (= April 2011) and 2011 (year-only date) in archives metadata. As you mention it, MySQL date field tolerates '2011-00-00' though no FAQs tell about it, and it's fine.
But then, I had to interface the MySQL database via ODBC and the date fields
are correctly translated, except the 'tolerated' dates (Ex: '2011-04-00' results empty in the resulting MySQL-ODBC-connected ACCESS database.
For that reason, I came to the conclusion that the MySQL date field could be converted in a plain VARCHAR(10) field : As long as we don't need specific MySQL date functions, it works fine, and of course, we can still use php date functions and your fine date_php2mysql() function.
I would say that the only case when a MySQL date field is needed
is when one needs complex SQL queries, using MySQL date functions in the query itself.
(But such queries would not work anymore on 'more or less precise' dates!...)
Conclusion : For 'more or less precise' dates,
I presently discard MySQL date field and use plain VARCHAR(10) field
with aaaa-mm-jj formated data. Simple is beautiful.
Since the data parts are all optional, would it be tedious to store the month, day, and year portions in separate integer fields? Or in a VARCHAR field? 2011-02-00 is not a valid date, and I wouldnt't think mysql or PHP would be excited about it. Test it out with str_to_time and see what kind of results you get, also, did you verify that the sorting worked right in MySQL? If the docs say that 1 through 31 is required, and it is taking 00, you might be relying on what is, in essence, a bug.
Since 2011-02-00 is not a valid date, none of PHP's formatting functions will give you this result. If it handled it at all, I wouldn't be surprised if you got 2001-01-31 if you tried. All the more reason to either store it as a string in the database, or put the month, day, and year in separate integer fields. If you went with the latter route, you could still do sorting on those columns.
I have also encountered this problem. I ended up using the PEAR Date package. Most date classes won't work with optional months or optional days, but the PEAR Date package does. This also means you don't need custom formatting functions and can use the fancy formatting methods provided by the Date package.
I have found this link in a textbook. This states that month and day values can be zero to allow for the possiblity of storing incomplete or unknown data
http://books.google.co.uk/books?id=s_87mv-Eo4AC&pg=PA145&lpg=PA145&dq=mysql+date+of+death+when+month+unknown&source=bl&ots=tcRGz3UDtg&sig=YkwpkAlDtBP1KKTDtqSyZCl63hs&hl=en&ei=Btf5TbL1NIexhAfkveyTAw&sa=X&oi=book_result&ct=result&resnum=8&ved=0CFMQ6AEwBw#v=onepage&q&f=false
If you pull your date in pieces from the database you can get it as if it's 3 fields.
YEAR(dateField) as Year, MONTH(dateField) as Month, DAY(dateField) as DAY
Then pushing those into the corresponding fields in the next bit of PHP will give you the result you're looking for.
$day = 0;
$month = 0;
$year = 2013;
echo $datestring;
$format = "Y";
if($month)
{
$format .= "-m";
if($day)
$format .="-d";
else
$day = 1;
}
else
{
$month = 1;
$day = 1;
}
$datestring = strval($year)."-".strval($month)."-".strval($day);
$date = date($format, strtotime($datestring));
echo $date; // "2013", if $month = 1, "2013-01", if $day and $month = 1, "2013-01-01"

Categories