Roy
Roy

Reputation: 49

php datetime insertion into mysql

I am trying to insert the datetime into a column in a mysql table.

 <?php

//Some code

date_default_timezone_set('Europe/London');

//Other variables defined also

$date_time = new DateTime();


$queryreg = mysql_query ("

    INSERT INTO users VALUES ('','$username','$password','$email','$website','$image','$date_time')

    ");



?>

However the browser states: "Catchable fatal error: Object of class DateTime could not be converted to string in C:\xampp\htdocs\design\register.php on line 181". Any idea why it is doing this? Many thanks in advance.

Upvotes: 0

Views: 2768

Answers (5)

jamesTheProgrammer
jamesTheProgrammer

Reputation: 1777

Provide a string format for the date, like this:

date_format(variable, "string format")

date_format($date_time, "%m/%d/%y"), for example.

Upvotes: 1

Igor Popov
Igor Popov

Reputation: 998

The best solution is to have timestamp field in table with default value CURRENT_TIMESTAMP.

But if you want to control manually this one then you need to convert DateTime object to a string like this:

<?php
//Some code
date_default_timezone_set('Europe/London');

//Other variables defined also
$date_time = new DateTime();

$queryreg = mysql_query("INSERT INTO users VALUES
      ('','$username','$password','$email','$website','$image',
      '{$date_time->format('Y-m-d H:i:s')}')");
?>

Upvotes: 0

shadyyx
shadyyx

Reputation: 16055

You have to use $datetime->format('Y-m-d H:i:s') for the insertion, like this:

INSERT INTO users VALUES ('', '$username', '$password', '$email', '$website', '$image', '{$date_time->format('Y-m-d H:i:s')}')

I also suggest not using mysql_* functions but rather learn using PDO with prepared statements or at least mysqli_* functions.

Also sanitize Your input to prevent SQL Injection.

Upvotes: 1

Marc B
Marc B

Reputation: 360562

$date = $date_time->format('Y-m-d H:i:s');

INSERT INTO .... VALUES (..., '$date');

Upvotes: 5

MrKiane
MrKiane

Reputation: 5013

It is because you are trying to typecase $date_time to string by surrounding it with '' in your SQL query. Either remove the surrounding quotes or convert to string by doing:

$date_time->format('Y-m-d H:i:s');

Upvotes: 1

Related Questions