Forum Moderators: coopster

Message Too Old, No Replies

date to datetime

         

gargoyle

9:03 am on Mar 3, 2008 (gmt 0)

10+ Year Member



Howdy all!
I thought at first to submit this into database section but this is about PHP form (and a bit MySQL database).

I have found several answers from different forums to my question about changing PHP date to MySQL datetime but they have all been just wrong. There's always those "use timestamp" or "use NOW()" answers but that is not what I'm looking for.
So here goes...
I have a form and in one of those textfields you can add date; it is because later admin can see from there when that article, or in user list, user is added. But I want that admin or mod can put any date he wants. I want that he has a possibility to insert ANY date he wants.

By the way, I'm using PHP 5 and MySQL 5.0.27.

And now the real problem: I type for example 21.2.2008 (notice dots!) and I fill other textfields as well. Then I press 'submit' and this is what I get: " Incorrect datetime value: '21.2.2008' ".
Well of course, in MySQL same would be 2008-02-21 (plus time). MySQL doesn't understand that order or especially those dots. (They have to be dots!)

I have noticed that it helps to put some code with message so here's some key portions of it:

...(snip)...

if(isset($_POST['add_form1']))
{

$somefield1 = $_POST['somefield1'];
$somefield2 = $_POST['somefield2'];
$add_date = $_POST['add_date'];
$query = "INSERT INTO list (somefield1, somefield2, add_date)
VALUES ('$somefield1', '$somefield2', '$add_date')";
mysql_query($query) or die(mysql_error($conn));

...(snip)...

I tried to change that
$add_date = $_POST['add_date']; into $add_date = date('d.m.Y');
but it didn't work. Well, how could it? That MySQL database is still expecting something else.

Next that important input part of form; as you can see there's always this day as default.

...(snip)...

<input type="text" name="add_date" size="10" value="<?php print (date("d.m.Y")); ?>">

...(snip)...

So plain and simple, you fill textfield in PHP form inserting (any) date as d.m.Y and MySQL database smiles and accepts it. That's it. Can it be done?

coopster

1:50 pm on Mar 3, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You, the programmer, must edit check and format the date prior to INSERT. Grab the date from the posted form value, peel it apart into the values expected by the instructions on your HTML entry form (d.m.Y), and then you can use PHP functions to checkdate [php.net]. Also, you should be validating the other form data too and at the very least using mysql_real_escape_string [php.net]. The practice you are using here is very unsafe. Never trust user-input!