php mysql insert date of birth - php

I would like some help here.
I'm having a registration form with fields like name, surname, dob (date of birth), email etc.
When I'm trying to insert into my database everything works fine but for the dob.
The dob I get it from 3 select-option menus like $_POST['year'], $_POST['month'], $_POST['day'], but i haven't find out yet how to put those 3 values in one (dob) in order to insert it in my database correct and not taking the value 0000-00-00.
Any help will be appreciated.

The dob I get it from 3 select-option menus like $_POST['year'], $_POST['month'], $_POST['day']
Just validate and concatenate:
$yr=(integer)$_POST['year'];
$mo=(integer)$_POST['month'];
$da=(integer)$_POST['day'];
if (($yr>1910 && $yr<(integer)date('Y'))
&& ($mo>0 && $mo<13)
&& ($da>0 && $da<32)) {
$mysqldate=sprintf("%04d-%02d-%02d", $yr, $mo, $da);
} else {
trigger_error('date is not valid');
}

Building on rootatwc's reply, one crucial factor when inserting into the database is that DATETIME values must be quoted just like strings.
$name = "Sepp";
$surname = "Blatter";
$dob=$_POST['year'] . '-' . $_POST['month'] . '-' . $_POST['day'];
"insert into birthdays (name, surname, dob) values ('$name', '$surname', '$dob')"
You will also find mysql is quite forgiving, for example June can be expressed as -06- or -6-
As for extracting all entries for a certain year, that is laughably easy - no need to put them into separate fields in your database:
select name from birthdays where YEAR(dob) = '1950';
EDIT
re-reading the question, it is not obvious that the OP is actually using a DATE field, hey, OP, use a DATE field - then you can browse your database and understand what dates are without having to try and decipher a 10 digit number... and you can use all the wonderful date functionality that Mysql comes with ...

How do you want them stored in your database? Do you want them as a UNIX Timestamp, or as some other format?
Without you knowing how you want them formatted, we can't help.
Either way, you should use mktime() to convert to UNIX Timestamp, and then date() when you know how you want it formatted.

If your Apache is on a Linux server, you can use timestamp. Why only on a Linux server? Because Linux understands negative timestamps and that you will probably need them if you have people born before 1.1.1970.
$timestamp = mktime(0,0,0,$month,$day,$year);
Save the timestamp as an int.
echo date('d.m.Y',$timestamp);
to echo it.

$timestamp=mktime(0,0,0,$_POST['month'],$_POST['day'],$_POST['year']);
$dob=date('Y-m-d',$timestamp);
The $dob value is ready to be inserted to your database
Or alternatively you could do:
$dob=$_POST['year'] . '-' . $_POST['month'] . '-' . $_POST['day'];
but you should escape the values first before inserting them to db, or use PDO

change DOB field to <input type="date" name="dob" class="datetime" /> html 5 would generate a datetimepicker for you. And then you can get it $_POST['dob']
And the dob field in database should be TIMESTAMP, DATETIME or DATE format, for universal date format.

Related

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.

strtotime not inserting into database

So Im scraping a website for data, and one piece of data that im scraping is the date of certain items.
The date of the items comes in the format "Wed 11th March, 2015".
I have been trying to then insert this into my mysql database. The structure of the database contains a column with "datapublished" as a Timestamp,
`feeddatapublished` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)
When updating the rest of the columns with the data it updates fine with the following code
$stmt = $dbh->prepare("INSERT INTO `feedsdata` (`id`, `feedid`, `feedurl`, `feedsummary`, `feedtitle`, `feeddatapublished`) VALUES (NULL, :feed_id, :feed_url, :feed_summary, :title, :datapublished)");
$stmt->bindParam(':feed_id', $feed_id);
$stmt->bindParam(':feed_url', $feed_url);
$stmt->bindParam(':feed_summary', $feed_summary);
$stmt->bindParam(':title', $feed_title);
$stmt->bindParam(':datapublished',$datepublished);
$stmt->execute();
I converted the string from the feed before passing it to be inserted with
$datepublished = strtotime(scrape_between($separate_result, "<span class=\"date\">", "</span>"));
scrape_between is a function I use for the scraping.
When echoing out the $datepublished I get the timestamp 1458155700, which isnt the correct timestamp from what i can see.
All other columns are updating as required, the only one which isnt is the datepublished one.
My two questions are
Is the reason its not updating because im passing a malformed timestamp to the mysql database
How can I generate a better timestamp from the format above, Ive checked the date function but I cant seem to get it to work.
The MySQL timestamp format is 2016-02-13 15:48:29 or Y-m-d H:i:s convert your unix timestamp to that format first, and then MySQL will accept it.
Either with
<?php
$datapublished = date("Y-m-d H:i:s", strtotime(scrape_between($separate_result, "<span class=\"date\">", "</span>")));
OR
your query to
$stmt = $dbh->prepare("INSERT INTO `feedsdata` (`id`, `feedid`, `feedurl`, `feedsummary`, `feedtitle`, `feeddatapublished`)
VALUES (NULL, :feed_id, :feed_url, :feed_summary, :title, from_unixtime(:datapublished))");
the problem is that strtotime is not smart enough to recognise the string so its best guess is 1458155700.
you can add an additional step to clean the date:
$scrape = scrape_between(...);
$cleanDate = preg_replace(
'/[a-z]+ ([0-9]{1,2})[a-z]+ ([a-z]+), ([0-9]{4})/i',
'$1 $2 $3',
$scrape
);
$datepublished = strtotime($cleanDate);
the preg_replace function uses a regular expression to remove the unnecessary parts.
If you know the date format used on the webpage you're scraping and it stays constant, you can use DateTime::createFromFormat() for safer and more controlled date parsing.
<?php
$datestring = "Wed 11th March, 2015";
$date = DateTime::createFromFormat("D dS F, Y", $datestring);
// Reset hours, minutes and seconds - otherwise the current time is used
$date->setTime(0, 0, 0);
// Format for MySQL database insertion
$datepublished = $date->format("Y-m-d H:i:s");

PHP to MySQL date formatting issue

I have a PHP/MySQL date formatting problem. Here, i create the date variables:
$checkDate = date("d/m/y H:i", time());
$datestrto = strtotime($checkDate);
Then i insert it to a mysql table with the column Datatype of bigint.
When i then, later on, when i need to echo the date, i use this code:
echo '<td>'.date("d/m/y H:i",$row['f_uploaded_date']).'</td>';
But istead of echo'ing the date in the format D/M/Y H:i, it echo'es the date in the format of m/d/y H:i.
Can anyone explain why this is happening, and how to fix it?
Thank you in advance,
Adam
When you insert it into the MySQL table do it like this:
INSERT INTO yourtable(something,somedate) VALUES('something',str_to_date('".$checkDate."','%d/%m/%y %H:%i'))
and when you pull it out from MySQL then do it like this:
SELECT *,date_format(somedate,'%D/%M/%Y %H:%i') as formateddate from yourtable
then in php you use:
$row['formateddate']
Hope it helps you :)
EDIT:
The complete code:
$ddate = date("d/m/y H:i", time());
$sql = "INSERT INTO files (rowID, file, mimetype, data, uploaded_by, uploaded_date, size, times_downloaded, description) VALUES (NULL, '$fileName', '$fileType', '$content', '$user', str_to_date('".$ddate."','%d/%m/%y %H:%i'), $fileSize, 0, '$description')";
So you convert a unix timestamp into a formatted date string then convert the formatted time string back into a unix timstamp and insert that into your database. Wouldn't it just be simpler to just insert the unix timestamp you got in the first place? Or not even bother with PHP code and
INSERT INTO sometable (id, f_uploaded_date)
VALUES ($id, UNIX_TIMESTAMP(NOW()))
?
I suspect the explicit problem you describe is due to the fact that strtotime expects date strings of format 99/99/9999 to be the american style of mm/dd/yyyy rather than dd/mm/yyyy as used in the UK.
First,
$checkDate = date("d/m/y H:i", time());
$datestrto = strtotime($checkDate);
is quite funny way of assigning time() frunction result to $datestrto variable.
Next, you don't need that variable either, as you just can use unix_timestamp() mysql function in the insert query.
Now to your question.
istead of echo'ing the date in the format D/M/Y H:i, it echo'es the date in the format of m/d/y H:i.
double-check your syntax. there is a typo somewhere.
You can pull a date format from your mysql database and then when converting to a php variable you can use:
$num=mysql_numrows($result);
$i=0;
while ($i <= $num) {
$date=mysql_result($result,$i,"Date");
$date = date('d-m-Y', strtotime($date));
echo $date."<br>";
}
Where $result is your mysql query result and "Date" is the name of the column. However I am unsure of using this method with the time.
--EDIT--
link: http://php.net/manual/en/function.date.php

retrieve date from Mysql and spilt it to the specific list

i am trying to retrieve date from Mysql db to my html form in order to edit the records, now the way i used to insert the date into the database was getting Year - Month - Day each from a list and then unite them in one variable like this :
$dob = $_POST['Year'] . '-' . $_POST['Month'] . '-' .$_POST['Day'];
this will insert the value of $dob like this format 0000-00-00 in my table
the problem is that how i will retrieve this variable and split it each element to its specific list
what i tried seems useless and wrong which is this code
$row['userDateOfBirth'] = $year . '-' . $month . '-' . $day ;
then put each variable to (example:year)
<option value="1920" selected="selected"><? echo $year ; ?></option>
this did not work , how can i do this ?
Assuming you've got an actual date/datetime field, you can do the splitting inside MySQL:
SELECT YEAR(datefield), MONTH(datefield), DAY(datefield), etc...
which gives you three separate fields containing the individual date components. You could also do things like explode('-', $datestr) in PHP to decompose 'yyyy-mm-dd' into individual yyyy, mm, and dd chunks.
Lots of options, it's up to you to pick which one is easiest/best for your particular problem.
You can handle that on the client (php) side.
$year = date('Y', strtotime( $row['userDateOfBirth'] ) );
if you have an invalid date, $year will have 1970.
You could use
$row['userDateOfBirth'] = date("Y-m-d", strtotime($mysqlResultRow['dateField']));
Where basically you're telling the date() function to return a formatted string of the time passed to it, in this case created via strtotime().
Date() reference. The above example returns the date in "2000-01-01", see the reference for selecting the appropriate format for your project.

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)

Categories