这个脚本:
<?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);
?>
给出这个输出:
input value: 2021.04.06 10:50:20
array(1) {
["MYDATE"]=>
array(1) {
[0]=>
string(19) "2021.04.06 10:50:20"
}
}
你可以做的事情:
- 在您输入的日期上输入
var_dump(),以显示其类型
- 在表格上做 DESC 以显示您的数据类型
我相信您添加它是为了进行测试,但在生产中您希望避免为每个连接运行 ALTER SESSION,因为这会增加开销。而是使用TO_DATE,或在 PHP 启动之前设置环境变量NLS_DATE_FORMAT 和NLS_LANG(两者都是必需的)。请参阅The Underground PHP and Oracle Manual中的全球化章节