How do you insert data into a MySQL date or time column using PHP mysqli and bind_param?
Asked
Active
Viewed 1.2e+01k times
5 Answers
17
Timestamps in PHP are integers (the number of seconds from the UNIX epoch). An alternative to the above is to use an integer type date/time parameter, and the MySQL functions FROM_UNIXTIME
and UNIX_TIMESTAMP
$stmt = $mysqli->prepare("INSERT INTO FOO (dateColumn) VALUES (FROM_UNIXTIME(?))");
$stmt->bind_param("i", $your_date_parameter);
$stmt->execute();
-
1@Rob: When I use this, the date set is 1970/01/01 – Hrishikesh Choudhari Apr 06 '11 at 11:39
-
1The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows). – Yevgeniy Afanasyev Nov 20 '14 at 00:41
3
For the current date/time you can use the MySQL standard routine. You do not have to prepare that.
$query = "INSERT INTO tablename ";
$query .= "VALUES(?,?,?,NOW()) ";
$preparedquery = $dbaselink->prepare($query);
$preparedquery->bind_param("iii",$val1,$val2,$val3);

Vincent
- 4,342
- 1
- 38
- 37
0
I used the date( ) function and this solved me the problem.
$stmt = $mysqli->prepare("INSERT INTO FOO (dateColumn) VALUES ?");
// 6/10/2015 10:30:00
$datetime = date("Y-m-d H:i:s", mktime(10, 30, 0, 6, 10, 2015));
$stmt->bind_param("s", $datetime);
$stmt->execute();

jcromeros1987
- 155
- 1
- 4
-1
first set the date & time using date() function-
$date=date("d/m/y");
$time=date("h:i:sa");
then pass it into the prepared statement, just like any other string variable-
$stmt = $mysqli->prepare("INSERT INTO FOO (dateColumn, timeColumn) VALUES (?,?)");
$stmt->bind_param("ss", $date , $time);
$stmt->execute();

Wijay Sharma
- 439
- 7
- 17
-
It is not working for me I get the error: `[Fatal error] Uncaught Error: Object of class DateTime could not be converted to string` I'm doing the same but I get this error. – S. W. G. Mar 04 '23 at 20:38