I am a newbie. I started php coding few days back. I want to copy a “datetime” datatype in php to fields that are of “date” and “time” datatype.
I have kept the field name datetime_info for the datetime value. It exists in try1 table. date is the name of field for “date” datatype and time is the name for “time” datatype. These two exist in try2 table.
Here is what I have written.
$result = mysql_query("SELECT * FROM try1");
while ($row = mysql_fetch_array($result))
{
$result_update = mysql_query("INSERT INTO try2 (date, time) VALUES ('".$row_team['datetime_info']."', '".$row_team['datetime_info']."')");
if (!$result_update)
die('Error: ' . mysql_errno() . mysql_error());
}
The values stored in “try1” table are:
id datetime_info
1 2008-10-02 00:00:00
2 2008-10-09 00:00:00
The expected response should be the date and time stored in respective fields. However, the output is
id date time
2 0000-00-00 00:00:00
3 0000-00-00 00:00:00
Can anyone explain me why and how? I tried a lot of sites but did not find any proper explanation for this. Thank you in anticipation.
Regards,
BasicGem
First of all, you shouldn’t have to use PHP to do the hard work here. MySQL is very powerful to do these kinds of tasks on it’s own.
Since you are copying all rows from table
try1intotry2(but splitting the datetime column), the following should work:What this does is: for every record found in
try1insert the following values intotry2:nullmeans use theauto_incrementfunctionality of theidcolumn intry2(this is presuming theidcolumn is indeed an auto incrementing primary key field)DATE( `datetime_info` )means use the DATE part of thedatetime_infocolumn oftry1TIME( `datetime_info` )means use the TIME part of thedatetime_infocolumn oftry1Simply doing
mysql_query( $sql )where$sqlis a string that represents above query should suffice then. No need to loop through any results first with PHP.I was gonna write a PHP solution as well, but others have already done so. I would have suggested this answer.