0

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.

1

5 Answers 5

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

INSERT INTO .... VALUES (..., '$date');
Sign up to request clarification or add additional context in comments.

Comments

1

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');

Comments

1

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.

Comments

1

Provide a string format for the date, like this:

date_format(variable, "string format")

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

Comments

0

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')}')");
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.