Solved

Date Rookie PHP

Posted on 2011-03-17
9
357 Views
Last Modified: 2012-05-11
Hi Experts,

Im a total rookie when it comes to formatting dates, ive read other posts but they dont seem to make much sense to me.

I have this code which i have attached which inputs the data into the database, but to get it OUT of the database or even before it goes in.. i want to format it to the following.

DD/MM/YYYY  OR whichever format is easiest to sort by as i will be sorting the results by date.

many thanks for your time.. my code is attached.

P.s how would i output the date in the format of dd/mm/yyyy is what im after.

many thanks again.
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<?php
if(isset($_POST['add']))
{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}


$submission_date = $_POST['submission_date'];

$sql = "INSERT INTO test ".
       "(submission_date) ".
       "VALUES ".
       "('$submission_date')";
mysql_select_db('newdatabase');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";


mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="600" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="250">Submission Date [ yyyy-mm-dd ]</td>
<td>
<input name="submission_date" type="text" id="submission_date">
</td>
</tr>
<tr>
<td width="250"> </td>
<td> </td>
</tr>
<tr>
<td width="250"> </td>
<td>
<input name="add" type="submit" id="add" value="Add Tutorial">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>

Open in new window

0
Comment
Question by:NeoAshura
  • 2
  • 2
  • 2
  • +3
9 Comments
 
LVL 8

Assisted Solution

by:Rik-Legger
Rik-Legger earned 125 total points
Comment Utility
When you ask the user for the following format [ yyyy-mm-dd ] than you can reformat it in this way:

list($year, $month, $day) = explode('-', $_POST['submission_date']);
$new_format = $day . '/'. $month . '/'. $year;

Open in new window

0
 
LVL 3

Assisted Solution

by:CombatGold1
CombatGold1 earned 125 total points
Comment Utility
If you're using the DATE data type in your MySQL database, it will physically store the date in YYYY-MM-DD. This is logical as sorting it ascending/descending will correctly order records by date.

When you retrieve your data from the database you can format it back to any format you like with this:
$rowTimestamp = strtodate($row['date']);
$rowDate = date("DD-MM-YYYY", $rowTimestamp);

Open in new window

The $rowDate variable will now contain the date in the format you wish, ready for you to echo.
0
 
LVL 6

Author Comment

by:NeoAshura
Comment Utility
@ Comnbat Gold Yes im using Date format in my table but i get an error when trying to use your code

How would i format it back?

Something like??


<?php
session_start();

error_reporting(E_ALL);
//test//
include 'myphp.php';

$rowTimestamp = strtodate($row['submission_date']);
$rowDate = date("DD-MM-YYYY", $rowTimestamp);

$sql="SELECT * FROM test WHERE submission_date='$rowDate'";
//echo "!!!!$sql!!!!";
$result=mysql_query($sql);
?>
0
 
LVL 17

Expert Comment

by:nanharbison
Comment Utility
The second line should have been
$rowDate = date("d/m/Y", $rowTimestamp);

Open in new window

0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 82

Accepted Solution

by:
hielo earned 125 total points
Comment Utility
Try:
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<?php
if(isset($_POST['add']))
{
	$submission_date = strtotime($_POST['submission_date']);
	if( $submission_date )
	{
     	$dbhost = 'localhost';
     	$dbuser = 'root';
     	$dbpass = '';
     	$conn = mysql_connect($dbhost, $dbuser, $dbpass);
     	if(! $conn )
     	{
     		die('Could not connect: ' . mysql_error());
     	}
     	$sql = sprintf("INSERT INTO `test` (`submission_date`) VALUES('%s')",date('Y-m-d',$submission_date) );
     
     	mysql_select_db('newdatabase');
     	$retval = mysql_query( $sql, $conn );
     	if(! $retval )
     	{
     		die('Could not enter data: ' . mysql_error());
     	}
     	echo "<div>Entered data successfully\n</div>";

		//assuming you have a column named `id`
		$sql="SELECT id as `Unique ID`, date_format('%m/%d/%Y',`submission_date`) as `Submitted On` FROM `test`";
		$res=mysql_query($sql, $conn) or die( mysql_error() );
		
		if( mysql_num_rows($res) )
		{
			$row=mysql_fetch_assoc($res);
			echo '<table border="1"><thead><tr><th>'.implode('</th><th>',array_keys($row)).'</th></tr></thead><tbody>';
			do{
				echo '<tr><td>'.implode('</td></td>',$row).'</td></tr>';
			}while( $row=mysql_fetch_assoc($res) );
			echo '</tbody></table>';
		}
     	mysql_close($conn);
	}
	else
	{
		echo "<div>Invalid date entered!</div>";
	}
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
	<table width="600" border="0" cellspacing="1" cellpadding="2">
		<tr>
			<td width="250">Submission Date [ yyyy-mm-dd ]</td>
			<td>
				<input name="submission_date" type="text" id="submission_date">
			</td>
		</tr>
		<tr>
			<td width="250"> </td>
			<td> </td>
		</tr>
		<tr>
			<td width="250"> </td>
			<td>
				<input name="add" type="submit" id="add" value="Add Tutorial">
			</td>
		</tr>
	</table>
</form>
<?php
}
?>
</body>
</html>

Open in new window

0
 
LVL 82

Expert Comment

by:hielo
Comment Utility
On my previous post, the arguments to date_format() are reversed - change:
date_format('%m/%d/%Y',`submission_date`)

 to:
date_format(`submission_date`, '%m/%d/%Y')
0
 
LVL 6

Author Comment

by:NeoAshura
Comment Utility
Will try when I get back to computer
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
This link should answer any questions you have about the subject.  Please read it over and try some of the examples, then post back with specific questions.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html

Executive summary:  All internal date representations are kept in ISO8601 format, which is date('c') in PHP.  All external representations are reformatted into the preferred view using strtotime() to turn the ISO format into a Unix timestamp, and date() to turn the Unix timestamp into a human-readable date/time string.  
http://us3.php.net/manual/en/function.strtotime.php
http://us3.php.net/manual/en/function.date.php
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 125 total points
Comment Utility
Define your submission_date column as MySQL DATETIME and use something like this...

HTH, ~Ray
// TRY TO MAKE A TIMESTAMP
$timestamp = strtotime($_POST['submission_date']);

// DID THAT WORK?
if (!$timestamp) die('BOGUS DATE');

// YES, IT WORKED, MAKE THE ISO8601 FORMAT DATE FOR THE DATA BASE
$internal_date = date('c', $timestamp);

Open in new window

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now