简体   繁体   中英

Insert date into sql database

My input date format is '%m-%d-%Y' (eg: 12/12/2012) and my Query for executing

"Insert into employeedetails(FirstName,LastName,JobTitle,StartedDate,Salary,CompanyName)  values ('"+fname+"','"+lname+"','"+job+"',STR_TO_DATE('"+date+"', '%m-%d-%Y'),'"+salary+"','"+company+"')";

while executing query it throws error about incorrect format

When i manually inserting date in this format (2012-12-12) it's working so i need the conversion from 12/12/2012 to 2012-12-12

USE DATE_FORMAT

The following script uses the DATE_FORMAT() function to display different formats. Example with now()

DATE_FORMAT(NOW(),'%b %d %Y %h:%i %p')
DATE_FORMAT(NOW(),'%m-%d-%Y')
DATE_FORMAT(NOW(),'%d %b %y')
DATE_FORMAT(NOW(),'%d %b %Y %T:%f')


Insert into employeedetails(FirstName,LastName,JobTitle,StartedDate,Salary,CompanyName)  values ('"+fname+"','"+lname+"','"+job+"',DATE_FORMAT(NOW(), '%m-%d-%Y'),'"+salary+"','"+company+"')";

You must consider the type of StartedDate field of your table to format data being inputted

then use specific formatting from type DATE , DATETIME , TIMESTAMP

The DATE, DATETIME, and TIMESTAMP Types

Date and Time Functions

by using DATE_FORMAT listed above the date and time functions then distinguising the right format for field type

DATE_FORMAT($datetoformat,'%Y-%m-%d');   // for date format
DATE_FORMAT($datetoformat,'YYYY-MM-DD HH:MM:SS');  // datetime format

As far as i can see you are saying your input date looks like

12/12/2012

but you give

'%m-%d-%Y'

to STR_TO_DATE. Which is not very plausible to me.

Shouldn't you give

'%m/%d/%Y'

to STR_TO_DATE?

in php you should use

    "Insert into employeedetails(FirstName,LastName,JobTitle,StartedDate,Salary,CompanyName)  values 
('".$fname."','".$lname."','".$job."','".date('d/m/Y')."','".$salary."','".$company."')";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM