Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sprintf() with date string

Status
Not open for further replies.

PCHomepage

Programmer
Feb 24, 2009
609
US
I'm trying to insert a date/time to MySQL using sprintf() but can't seem to work out how to do it. The date and time are formatted as 2014-10-01 09:30:00 but I'm not sure how to format the data to insert it. I tried '%04d-%02d-%02d %02d:%02d:%02d' but get an error of too few arguments. What am I doing wrong?

Code:
$PostID = (isset($_POST["ID"]) && !empty($_POST["ID"])) ? $_POST["ID"] : "";
$Title = (isset($_POST['Title'])) ? $_POST['Title'] : NULL;
$StartDate = (isset($_POST['StartDate'])) ? $_POST['StartDate'] : NULL;
$StartTime = (isset($_POST['StartTime'])) ? $_POST['StartTime'] : NULL;
$FormattedDateTime = "$StartDate $StartTime";
$FormattedDateTime = date('Y-m-d H:i:s', strtotime($FormattedDateTime));

// Insert record
if (isset($_POST) && (isset($_POST["insert"]) || isset($_POST["update"]))) :
	$sqlInsert = sprintf("INSERT INTO calendar (Title, Start)
				VALUES ('%s','%04d-%02d-%02d %02d:%02d:%02d')",
				$Title,
				$FormattedDateTime);
    $PostID = DBConnect($sqlInsert, "Insert", "dbname");
	$Message = "A new calendar entry has been created.";
endif;
 
Just use a single '%s' as placeholder. The date() function already takes care of the formatting.

The way you have constructed the sprintf is to require 6 arguments for the date piece (one for each of y m d h mins and secs) but you have only supplied one (the preformatted date).
 
I had tried that originally but it failed although it works now! Thank you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top