php mysql datetime
I have two tables in MySQL, and each table has its own datetime field. I want to copy the datetime of table A to overwrite the datetime of table B. I use PHP.
$result = mysql_query("select *
from A
开发者_JS百科 where id = $key");
$row = mysql_fetch_array($result);
print $row[2]."\n"; // $row[2] is the datetime field
mysql_query("update B
set date_cal = $row[2]
where id = $key") // try to overwrite datetime in table B
$row[2] has the string representation of datetime field.
But the overwrite operation does not take effect. How to do to overwrite datetime field of table B using php?
If I insist using $row[2] to assign the new datetime field rather running mysql_query again, how to do?
I believe you'll need to wrap the date in quotes in your update query.
mysql_query("update B set date_cal=$row[2] where id=$key")
Should be
mysql_query("update B set date_cal='$row[2]' where id=$key")
On another note, I'd suggest that you don't access your fields by index when you're doing a SELECT *
query. If you add another field to your database, $row[2]
could end up referring to something else. If you instead call $row = mysql_fetch_assoc($result);
, you can refer to it by field name, eg
mysql_query("update B set date_cal='{$row['date_field]}' where id=$key")
If I understand that correctly, you can do the same from within your query:
update B
set date_cal = (select date_cal from A where id = {$key})
where id = $key
精彩评论