This script:
<?php
/*
drop table mytable purge;
create table mytable (id number, mydate date);
*/
error_reporting(E_ALL);
ini_set('display_errors', 'On');
$c = oci_connect("hr", "welcome", "localhost/XE");
if (!$c) {
$m = oci_error();
trigger_error('Could not connect to database: '. $m['message'], E_USER_ERROR);
}
$sql = <<<'END'
INSERT INTO MYTABLE(ID,MYDATE) VALUES(:ID,to_date(:MYDATE,'YYYY.MM.DD HH24:MI:SS'))
END;
$id = 1;
//$mydate = '2017.07.21 08:59:26'; // also works
$mydate = date("Y.m.d H:i:s");
echo "input value: ", $mydate, "\n\n";
$s = oci_parse($c, $sql);
if (!$s) {
$m = oci_error($c);
trigger_error('Could not parse statement: '. $m['message'], E_USER_ERROR);
}
$r = oci_bind_by_name($s, ':id', $id);
if (!$r) {
$m = oci_error($s);
trigger_error('Could not bind a parameter: '. $m['message'], E_USER_ERROR);
}
$r = oci_bind_by_name($s, ':mydate', $mydate);
if (!$r) {
$m = oci_error($s);
trigger_error('Could not bind a parameter: '. $m['message'], E_USER_ERROR);
}
$r = oci_execute($s, OCI_NO_AUTO_COMMIT);
if (!$r) {
$m = oci_error($s);
trigger_error('Could not execute statement: '. $m['message'], E_USER_ERROR);
}
// Fetch back the data
$s = oci_parse($c, "select to_char(mydate, 'YYYY.MM.DD HH24:MI:SS') as mydate from mytable");
if (!$s) {
$m = oci_error($c);
trigger_error('Could not parse statement: '. $m['message'], E_USER_ERROR);
}
$r = oci_execute($s, OCI_NO_AUTO_COMMIT);
if (!$r) {
$m = oci_error($s);
trigger_error('Could not execute statement: '. $m['message'], E_USER_ERROR);
}
oci_fetch_all($s, $r);
var_dump($r);
oci_rollback($c);
?>
gives this output:
input value: 2021.04.06 10:50:20
array(1) {
["MYDATE"]=>
array(1) {
[0]=>
string(19) "2021.04.06 10:50:20"
}
}
Things you can do:
- do a
var_dump() on your input date, to show its type
- do a DESC on the table to show your datatype
I believe you'd added it for testing, but in production you would want to avoid running ALTER SESSION for each connection, since this adds overhead. Instead use the TO_DATE, or set the environment variables NLS_DATE_FORMAT and NLS_LANG (both are needed) before PHP starts. See the Globalization chapter in The Underground PHP and Oracle Manual