Page 1 of 1

Date saving problem

Posted: Wed May 25, 2011 12:04 pm
by shinstar
hy every one i have two files one is index.php and second insert.php as follow,

index.php

Code: Select all



<html>
<body>

<form action="insert.php" method="post">
Time <input type="text" name="time" />
<input type="submit" />
</form>

<?php
$ctime = date('h:i:s A');
echo "Current time is : " . $ctime ;
echo "<br>";

$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("time", $con);

$result = mysql_query("SELECT * FROM time");

while($row = mysql_fetch_array($result))
  {
  echo date('h:i:s A', strtotime($row['time']));
  
  echo "<br />";
  }

mysql_close($con);
?> 


</body>
</html> 
here is my insert.php file code,

Code: Select all


<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("time", $con);

$sql="INSERT INTO time (time )
VALUES
('$_POST[time]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";
echo "<br>";
echo "<a href='index.php'>Home</a>";

mysql_close($con)
?>

this code work fine but the form which submit the value of time in database whos code is in index.php file above,
i have to enter time in the form text field like this 17:00 and it save the value in database but,
i want to enter time in the form text field like this 05:00 PM which automatically save the value in database as 17:00
what should i do with the code help me please
thanks

Re: Date saving problem

Posted: Wed May 25, 2011 1:31 pm
by gooney0
Here is how I'd approach this:

I like to store dates in MySQL as "datetime" then convert to whatever I want. In your case I'd:

Convert the time the user submitted:

Code: Select all

$timestamp=strtotime($_POST["time"]);

// $timestamp is now a timestamp of 5pm

$saveme=date("G:i", $timestamp);

// $saveme is now 24hour:minute version or 17:00
My code is untested. so check the docs for details:

http://us3.php.net/manual/en/function.strtotime.php

http://us2.php.net/manual/en/function.date.php

Also you need to use mysql_real_escape_string on the time before you insert it otherwise you risk attack.

http://us3.php.net/manual/en/function.m ... string.php

Re: Date saving problem

Posted: Wed May 25, 2011 2:11 pm
by shinstar
i dont understand where should i put your code in my coding?