How do i make a PHP form use a specific date format Mask / Validation....

I------have a simple data entry form that I would like to be able to have the Date and Time field be validated so it is on the correct format when being added to the database.  We use this date time field to turn on or off special pricing on products.
In the code below I enter the Starting Date in the correct format "YYYY/MM/DD 00:00:00" on my form and it write to the data base.  I like to have that field "StartingDate" validated on submit.
What is the best solution for this type of validation?

here is my test form:
-------------------------------------------------------------------------------------
<html>
 <head>
 </head>
 <body>
 <form action="insert.php" method="post">
 Item Number: <input type="text" name="ItemNumber">
 Sale Start Date: <input type="datetime" name="StartingDate">
 Sale End Date: <input type-"datetime" name="EndingDate">
 Sale Price: <input type="text" name="SalePrice">
 <input type="submit" name="submit">
 </form>

 


<?php
if (isset($_POST['submit'])){                                              /*only if the submit buttonis presseed*/


 $con = mysql_connect("Datebase location","Logon Name","Passowrd");
 // Check connection
 if (!$con) {
   die ('Could not Connect to MySQL: ' . mysql_error());
 }

mysql_select_db("biomas",$con);
 // escape variables for security
/*$ItemNumber = ($con, $_POST['ItemNumber']);
$StartingDate = ($con, $_POST['StartingDate']);
$EndingDate = ($con, $_POST['EndingDate']);
$SalePrice = ($con, $_POST['SalePrice']);  */

$sql = "INSERT INTO ITProductSale (ItemNumber, StartingDate, EndingDate, SalePrice)
VALUES ('$_POST[ItemNumber]','$_POST[StartingDate]','$_POST[EndingDate]','$_POST[SalePrice]')";

mysql_query ($sql, $con);

/*if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con)); */

echo "1 record added";

mysql_close($con);
}
 ?> 

</body>
 </html>

Open in new window


-------------------------------------------------------------------------
Scott JohnstonIT Manager Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
According to this page http://www.w3schools.com/html/html5_form_input_types.asp , only Safari and Opera support type="datetime".

I always use <select> dropdowns with the acceptable values as the only options.  I then combine them appropriately in the PHP page that follows.  That way, random values can't be submitted.  There is a some sample code on this page: http://www.dzone.com/snippets/html-select-list-combo-allows
0
Ray PaseurCommented:
How to process date / time values in PHP and MySQL (it's a common question):
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html

If you still have any questions after you read the article, please post back and we'll be glad to help.

And from the look of the code, you may also want to read this article about how to use PHP and MySQL:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
0
Scott JohnstonIT Manager Author Commented:
I have started from scratch with my coding and I have everything working perfectly but when I retrieve data from MySQL data it will only display the date and not the time.
My database has the date time stored like yyyy-mm-dd hh:mm:ss.

I been fulling around with the DATETIME type on the Input statement but I cannot get the time stamp to display.  I've tried text for type , I've tried Date for type ....not sure what else to do?
I guessing I need to update my value with som special coding?

-----------------------------------------------------------------------------


while ($record = mysql_fetch_array($mydata)){
echo "<form action = updatedeletedata4.php method=post>";
      echo "<tr>";
      echo "<td>" . "<input type=text name=ItemNumber value=" . $record['ItemNumber'] . " </td>";
      echo "<td>" . "<input type=datetime name=StartingDate value=" . $record['StartingDate'] . " </td>";
      echo "<td>" . "<input type=datetime name=EndingDate value=" . $record['EndingDate'] . " </td>";
      echo "<td>" . "<input type=text name=SalePrice value=" . $record['SalePrice'] . " </td>";
      echo "<td>" . "<input type=hidden name=hidden value=" . " </td>";
      echo "<td>" . "<input type=submit name=update value=update" . " </td>";
      echo "<td>" . "<input type=submit name=delete value=delete" . " </td>";
      echo "</tr>";
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Scott JohnstonIT Manager Author Commented:
Here is a copy of my new coding....

<html>
<head>
</head>
<body>
      <?php
$con = mysql_connect("domain.com","Account","password");
 // Check connection
 if (!$con) {
   die ('Could not Connect to MySQL: ' . mysql_error());
 }

mysql_select_db("databasename",$con);


if (isset($_POST['update'])){
$UpdateQuery = "Update ITProductSale set ItemNumber='$_POST[Itemnumber]', StartingDate='$_POST[StartingDate]', EndingDate='$_POST[EndingDate]', SalePrice='$_POST[SalePrice]'
where  ItemNumber='$_POST[hidden]'";
mysql_query($UpdateQuery, $con);

};


if (isset($_POST['deleteupdate'])){
$DeleteQuery = "DELETE from ITProductSale where ItemNumber='$_POST[hidden]'";
mysql_query($DeleteQuery, $con);

};



$sql = "Select * from biomas.ITProductSale";
$mydata = mysql_query($sql,$con);
echo "<table border=1>
<tr>
<th> Item Number </th>
<th> Starting Date / Time </th>
<th> Ending Date / Time </th>
<th> Sale Price </th>
</tr>";
while ($record = mysql_fetch_array($mydata)){
echo "<form action = updatedeletedata4.php method=post>";
      echo "<tr>";
      echo "<td>" . "<input type=text name=ItemNumber value=" . $record['ItemNumber'] . " </td>";
      echo "<td>" . "<input type=datetime name=StartingDate value=" . $record['StartingDate'] . " </td>";
      echo "<td>" . "<input type=datetime name=EndingDate value=" . $record['EndingDate'] . " </td>";
      echo "<td>" . "<input type=text name=SalePrice value=" . $record['SalePrice'] . " </td>";
      echo "<td>" . "<input type=hidden name=hidden value=" . " </td>";
      echo "<td>" . "<input type=submit name=update value=update" . " </td>";
      echo "<td>" . "<input type=submit name=delete value=delete" . " </td>";
      echo "</tr>";
echo "</form>";
}

echo "</table>";
mysql_close($con)

?>

</body>
</html>
0
Ray PaseurCommented:
If you're new to PHP and MySQL, this article can help you get a foundation in how the technologies work.  It can point you to some good learning resources, and more importantly, steer you away from the many terrible examples of PHP code that litter the internet.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

You must get off MySQL - this is not optional!
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

Please, please read the article!  It tells you everything you need to know about how to handle date/time values in PHP and MySQL.  
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html

Here is a code snippet that will show you how to use PHP strtotime() and date().  These two functions play together in ways that are almost magical.  Use strtotime() to turn external input into a UNIX timestamp.  Use date() to turn the UNIX timestamp into a formatted date string.  For internal representations of the date/time values and for communications with MySQL you will use date('c') to get the ISO-8601 datetime string.
http://iconoun.com/demo/strtotime.php

<?php // demo/strtotime.php
error_reporting(E_ALL);

// RESPONSE STRING HERE
$obuff = NULL;

// MAN PAGE http://php.net/manual/en/datetime.formats.relative.php
// MAN PAGE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// IF WE HAVE INPUT FROM THE URL QUERY STRING
if (!empty($_GET["s"]))
{
    // COLLECT THE OUTPUT BUFFER
    ob_start();

    // USE strtotime() FUNCTION TO MAKE A TIMESTAMP
    // MAN PAGE: http://php.net/manual/en/function.strtotime.php
    $unix_timestamp = strtotime($_GET["s"]);

    // TEST FOR SUCCESS OR FAILURE
    if ($unix_timestamp === FALSE)
    {
        echo "<strong>HONK!</strong><br /> <u>{$_GET["s"]}</u> NOT USEFUL WITH strtotime() <br/><br/><br/><br/>";
    }

    // ON SUCCESS, PRINT THE RESULTS
    else
    {
        echo "<strong>BINGO</strong><br /> <strong><u>{$_GET["s"]}</u></strong> WORKS WITH strtotime() <br/>";
        echo "THE INTEGER TIMESTAMP VALUE IS ";
        echo number_format($unix_timestamp) . "<br />";

        // FORMAT ISO AND HUMAN-READABLE DATES
        // MAN PAGE: http://php.net/manual/en/function.date.php
        $y = date('c', $unix_timestamp);
        echo "THE ISO8601 DATETIME STRING IS $y<br />";
        $z = date('l dS \o\f F Y g:i:s A', $unix_timestamp);
        echo "THE TEXTUAL DATE IS $z<br />";
    }

    // RECOVER THE RESPONSE FROM THE OUTPUT BUFFER
    $obuff = ob_get_clean();

} // END OF PROCESSING INPUT

$tzone = date_default_timezone_get();
$phpvs = phpversion();

// CREATE THE HTML FORM USING HEREDOC NOTATION
$htmls = <<<HTMLS
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="iso-8859-1" />
<title>PHP strtotime()</title>
</head>

<body onload="document.f.s.focus()">

$obuff

<form name="f" method="get">
<br />TO TEST A STRING FOR A VALID DATE/TIME, TYPE IT HERE:<input name="s" />
<input type="submit" value="GO" />
</form>

<br/><strong>Note: Your local time may vary.  This server is in $tzone</strong>
<br/>Current PHP version is $phpvs
<br/>TRY TESTING SOME OF THESE STRINGS (CLICK THE LINK, OR COPY AND PASTE INTO THE FORM):
HTMLS;

echo $htmls;

// DEFINE A FUNCTION TO CREATE A TEST CASE
function t($str)
{
    echo PHP_EOL
    . '<br/>'
    . '<a href="http://iconoun.com/demo/strtotime.php?s='
    . urlencode($str)
    . '">'
    . $str
    . '</a>'
    ;
}

// USE THE FUNCTION TO CREATE A FEW TEST CASES
t('- 3 hours');
t('tomorrow');
t('tomorrow 3:15:25 pm');
t('March 15, 1986');
t('yesterday');
t('yesterday + 1 week');
t('next year');
t('now');
t('now + 627 hours 15 minutes');
t('tomorrow midnight');
t('tomorrow 1:35pm');
t('last Tuesday');
t('three days ago');
t('last Friday + 2 weekdays');
t('- 3 days');
t('A TIME');
t('A BOGUS TIME');
t('s time');
t('t time');
t('u time');
t("Avogadro's Constant");
t("Wednesday November, 10 2010 1:01pm");
t("Wednesday, November 10 2010 1:01pm");
t("First Tuesday 2005"); echo " works, but not the way you might think";
t("Last day of January + 1 Month"); echo " works, but not the way you might think";
t("January 31 + 1 Month"); echo " works, but not the way you might think";
t('-1000000000 seconds'); echo " one billion";
t('+1000000000 seconds');
t('42'); echo " and thanks for all the fish!";

// END OF PAGE
echo '</body></html>';

Open in new window

0
Scott JohnstonIT Manager Author Commented:
Well you guidance is not very help full, it really seems to confuse me more than help me.....Sorry,  Ray as I see it, I will not be able to get the answer from this users group.

I was hoping to learn something, not have to ready a lecture.

I will keep on trying to learn something new but reading tons of documentation about why or why I should not use MYSQL, or information about DATE matrix's, is nothing but confusing, of course it is very informative, but I am a hands on learned.

I learn the best by examples, so I can go through trial and error..

So sorry,

Thank you
0
Ray PaseurCommented:
Try the examples posted here!
http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28506885.html#a40291171

But seriously, if you don't read the articles you're handicapping yourself.  This is stuff every PHP programmer knows.
0
Scott JohnstonIT Manager Author Commented:
Ray, I appreciate all your help and your links and I do read them, maybe by me reading the documents and having some examples I will be able to put it all together.  Reading documentation can be very difficult for me to retrieve the information I am looking for because I have no one to review what I have read to make sure I understand and then try to apply what I have just read.

I am currently doing a program that will have a form that will allow me to input data, then I like to use that data to query against the MYSQL data and then display the fields in the database and then make changes to the displayed data, after which would then run a update query to update the date in MYSQL.
I am trying to create a utility for my end user so that they can make direct changes to the MYSQL data and not have to request me to make the change.  (Kind of a simple admin utility for managing a Sales Price on our web site, the sales price is keyed on a item number and then we have a field that is used for start date and time, and end date and time, then sale price.  This is why I was trying to get the date time info.)

After reading about the MYSQL and PHP 5.5...I not sure what I need to do?  but at this time that is another story I will have to address.

I just feel it is easier to learn from example.

I been going through a 40 lesson PHP course (So far I am self taught)and I have learned quit a bit.

Thank you again, I going to keep on trucking, I getting better in understanding simple PHP code.  It can be very hard to learn when you are learning just from tutorials and manuals.
0
Dave BaldwinFixer of ProblemsCommented:
Details are important in programming.  And since your 'exact' example isn't going to be found most of the time, you need to get past using just examples and get into reading the documentation.  For example, my first post point out that type=datetime is only supported in Safari and Opera, not in IE, Firefox, and Chrome.  But the last code you posted still shows it.  Are you using only Safari and Opera?

I am also a self-taught programmer and I am one of the top experts here in PHP.  Whenever I am programming in PHP, I constantly refer to the pages on http://www.php.net/ to make sure I get the syntax right.  Ray's demo code is 'littered' with links to the appropriate pages on http://www.php.net/ .  For javascript, I usually look at the javascript pages on W3Schools http://www.w3schools.com/default.asp .  And for HTML validation, I use the 'Validator' on http://www.w3.org/ .  When in doubt, look it up.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
I am currently doing a program that will have a form that will allow me to input data, then I like to use that data to query against the MYSQL data and then display the fields in the database and then make changes to the displayed data, after which would then run a update query to update the date in MYSQL.
Of course!  Everyone does that.  It's so common a design pattern that it has a name: A Table Maintenance Script.

Totally agree with Dave: When in doubt, look it up.  I would also add, "make a copy, try a few changes, decide which you like best and store the code and data in a teaching example so you can refer back to it in the future."  That way you don't have reinvent any wheels, and over time you will have built a library of your own preferred solutions.  It's not rocket science, it just takes time and focus.
0
Scott JohnstonIT Manager Author Commented:
I agree with both of you regarding reading documentation, it just sometime is hard to get a complete understanding.  I been doing both http://www.w3schools.com/default.asp , and www.php.net.  I get a lot information from both of these sites.  I also been using a site Lecture Snippets, it has some very good information.  I am moving forward and appreciate you insight to my questions.  At this time I still have not gotten the Date format to work correctly.
0
Ray PaseurCommented:
First quote:
I like to have that field "StartingDate" validated on submit.
Last quote:
I still have not gotten the Date format to work correctly.
I don't know what else to tell you.  If you read the man page for PHP strtotime() and don't "get it" I would expect a follow-on question about best practices in handling date/time values in PHP and MySQL.

There's one other bit of documentation you might want to read: The E-E Grading Guidelines.  You're expected to explain a marked-down grade!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.