Solved

Date Rookie PHP

Posted on 2011-03-17
9
365 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
  • +3
9 Comments
 
LVL 8

Assisted Solution

by:Rik-Legger
Rik-Legger earned 125 total points
ID: 35158267
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
ID: 35158271
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
ID: 35158361
@ 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
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
LVL 17

Expert Comment

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

Open in new window

0
 
LVL 82

Accepted Solution

by:
hielo earned 125 total points
ID: 35158686
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
ID: 35158774
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
ID: 35159359
Will try when I get back to computer
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 35173609
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 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 125 total points
ID: 35173619
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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

752 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