mikecao / sparrow

A simple database toolkit for PHP
MIT License
289 stars 68 forks source link

MySQL Function NOW() #24

Closed artyuum closed 7 years ago

artyuum commented 8 years ago

Hi, I would like to execute a query like this : INSERT INTO logs (name, action, creation) VALUES ('test', 'test', NOW())

Here is what I've tried so far : $data = array('username' => 'test', 'action' => 'test', 'creation' => now()); $db->from('logs')->insert($data)->execute();

But unfortunately this doesn't work as PHP interprete 'now()' as a PHP function. I also tried to write "now" instead of "now()" but it returns "0000-00-00 00:00:00" instead of the current datetime.

So I would like to know, is it possible to execute MySQL functions using your database toolkit please ?

mikecao commented 8 years ago

Unfortunately there is no way to send string values that won't get escaped.

But you can use a PHP equivalent function to NOW().

function now() {
  return date("Y-m-d H:i:s");
}

$data = array('username' => 'test', 'action' => 'test', 'creation' => now());
artyuum commented 8 years ago

Actually, I want to use the SQL NOW() function because my PHP server is separated from my SQL server, so the time is different. But I will use the php-way to get the current datetime for the moment.

Thanks.

mikecao commented 8 years ago

In that case you can use the DateTime object, then use the setTimezone method on it to keep your values in sync.

function now() {
  $tz = new DateTimeZone("Europe/Madrid");
  $now = new DateTime();
  $now->setTimezone($tz);
  return $now->format("Y-m-d H:i:s");
}
artyuum commented 8 years ago

Thanks, I'll try that.