?
Solved

Date Rookie PHP

Posted on 2011-03-17
9
Medium Priority
?
368 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 500 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 500 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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 500 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 111

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 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 500 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses

719 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