在 php 中获取 DATETIME 并将其发布到 MySQL 以保持事务一致性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10129180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:27:21  来源:igfitidea点击:

Get DATETIME in php and post it to MySQL for transaction consistency

phpmysqldatetimetransactionsinnodb

提问by Maverick

Here is a link to the reason behind this question: NOW() for DATETIME InnoDB Transaction guaranteed?

这是此问题背后原因的链接: NOW() for DATETIME InnoDB Transaction 有保证吗?

So to ensure a single transaction with any number of queries (20+queries for example) has a 100% accurate and consistent NOW()value accross multiple tables, what is the php way to assign a variable equivalent of DATETIME using NOW() (not current TIMESTAMP).

因此,为了确保具有任意数量查询(例如20 多个查询)的单个事务在多个表中具有 100%准确和一致的 NOW()值,php 使用 NOW() 分配等效于 DATETIME 的变量的方法是什么(不是当前时间戳)。

回答by elxordi

One way could be:

一种方法可能是:

<?php
$nowFormat = date('Y-m-d H:i:s');
$sql = "INSERT INTO table SET field='$nowFormat'";
$sql2 = "INSERT INTO table SET field='$nowFormat'";
...

回答by Marc B

Do it in MySQL, so you don't involve PHP at all:

在 MySQL 中做,所以你根本不涉及 PHP:

select @now := now();

insert into .... values (@now)
select from ... where x=@now
etc....

回答by Ariel

You can do:

你可以做:

<?
$now = time();
$sql = "INSERT INTO table SET field=FROM_UNIXTIME($now)";
$sql2 = "INSERT INTO table SET field=FROM_UNIXTIME($now)";
...

This avoids any possible issues of timezones, or local date formats.

这避免了时区或本地日期格式的任何可能问题。