Since MySQL evidently cannot automatically insert the function now() in a datetime field in adding new records like some other databases, based on comments, I\'m explicitly tryi
Like Pekka said, it should work this way. I can't reproduce the problem with this self-contained example:
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->exec('
CREATE TEMPORARY TABLE soFoo (
id int auto_increment,
first int,
last int,
whenadded DATETIME,
primary key(id)
)
');
$pdo->exec('INSERT INTO soFoo (first,last,whenadded) VALUES (0,1,Now())');
$pdo->exec('INSERT INTO soFoo (first,last,whenadded) VALUES (0,2,Now())');
$pdo->exec('INSERT INTO soFoo (first,last,whenadded) VALUES (0,3,Now())');
foreach( $pdo->query('SELECT * FROM soFoo', PDO::FETCH_ASSOC) as $row ) {
echo join(' | ', $row), "\n";
}
Which (currently) prints
1 | 0 | 1 | 2012-03-23 16:00:18
2 | 0 | 2 | 2012-03-23 16:00:18
3 | 0 | 3 | 2012-03-23 16:00:18
And here's (almost) the same script using a TIMESTAMP field and DEFAULT CURRENT_TIMESTAMP:
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->exec('
CREATE TEMPORARY TABLE soFoo (
id int auto_increment,
first int,
last int,
whenadded TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
primary key(id)
)
');
$pdo->exec('INSERT INTO soFoo (first,last) VALUES (0,1)');
$pdo->exec('INSERT INTO soFoo (first,last) VALUES (0,2)');
sleep(1);
$pdo->exec('INSERT INTO soFoo (first,last) VALUES (0,3)');
foreach( $pdo->query('SELECT * FROM soFoo', PDO::FETCH_ASSOC) as $row ) {
echo join(' | ', $row), "\n";
}
Conveniently, the timestamp is converted to the same datetime string representation as in the first example - at least with my PHP/PDO/mysqlnd version.