简体   繁体   English

在插入时返回MySQL时间戳

[英]Return MySQL timestamp on insert

When I perform an insert statement to a MySQL database in PHP, is there a way to return the auto-generated timestamp or do I need a separate call to the database to retrieve the data? 当我在PHP中对MySQL数据库执行insert语句时,有没有办法返回自动生成的时间戳,还是需要单独调用数据库来检索数据?

Edit: I forgot that MySQL doesn't use epoch dates. 编辑:我忘了MySQL不使用纪元日期。 I decided to just use an autoincrementing integer and a stored procedure. 我决定只使用自动增量整数和存储过程。

You need to make a separate request to get that information. 您需要单独请求获取该信息。 You can only get the last insert ID of auto incremented tables when doing an INSERT. 在执行INSERT时,您只能获取自动递增表的最后一个插入ID。

Use a multi-statement query. 使用多语句查询。

  1. Select the current timestamp into a variable. 选择变量的当前时间戳。
  2. insert the row with the timestamp. 插入带有时间戳的行。
  3. return (select) the variable to php. 将变量返回(选择)到php。

As far as I know, it is possible for last inserted ID if the ID was set as AUTO_INCREMENT ed. 据我所知,如果ID设置为AUTO_INCREMENT ed,则最后插入的ID可能。 But for timestamp, I'll advise you to create a stored procedure so you will only have single request on the database. 但是对于时间戳,我建议你创建一个stored procedure这样你就只能在数据库上有一个请求。 Remember that connection into database is costly. 请记住,与数据库的连接成本很高。

You can return a last inserted id after insert , like: 您可以返回last inserted idinsert ,如:

<?php
$sql=mysql_query("INSERT INTO <TABLE> VALUES (?,?)");
return mysql_insert_id();
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM