Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Date Rookie PHP

Posted on 2011-03-17
9
Medium Priority
?
372 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 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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The title says it all. Writing any type of PHP Application or API code that provides high throughput, while under a heavy load, seems to be an arcane art form (Black Magic). This article aims to provide some general guidelines for producing this typ…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses

564 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