9

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

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).

Community
  • 1
  • 1
Maverick
  • 1,123
  • 5
  • 16
  • 30

3 Answers3

18

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'";
...
elxordi
  • 476
  • 3
  • 11
  • Be careful if the PHP server and Mysql server do not have the same default timezone. See my answer for an alternative without this problem. – Ariel Jun 06 '13 at 08:09
4

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

select @now := now();

insert into .... values (@now)
select from ... where x=@now
etc....
Marc B
  • 356,200
  • 43
  • 426
  • 500
3

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.

Ariel
  • 25,995
  • 5
  • 59
  • 69