从HTML日期表单中获取日期,并使用PHP将其插入到PostgreSQL表中

时间:2016-01-31 19:42:37

标签: php forms postgresql date sql-insert

我有一个带有日期

的HTML表单
<input type="date" name="mydate">

这就是它的样子:date form

我的PHP脚本在提交表单时启动。它或多或少看起来像这样:

$mydate = $_POST['mydate'];
$query = "insert into datetable(when) values({$mydate})";
$res = pg_query($db, $query);

它只是不起作用。当我尝试在psql CLI中手动运行生成查询时,我收到如下错误:

ERROR:  column "when" is of type date but expression is of type integer 
LINE 1: ..., when) values (1990-01-01...
                           ^ 
HINT:  You will need to rewrite or cast the expression.

但是我不知道怎么做。

我尝试在PHP中使用mydatedate()转换timetostr。我也试图用to_char(), to_date()做一些事情。但是我仍然无法做任何事情让它运行...

1 个答案:

答案 0 :(得分:1)

您应该将日期作为字符串传递。几个例子。

$mydate = pg_escape_literal($_POST['mydate']);
/*        ^^^^^^^^^^^^^^^^^ */
$query = "insert into datetable(when) values({$mydate})";
$res = pg_query($db, $query);


$mydate = pg_escape_string($_POST['mydate']);
/*        ^^^^^^^^^^^^^^^^                   v         v */
$query = "insert into datetable(when) values('{$mydate}')";
$res = pg_query($db, $query);


$mydate = $_POST['mydate'];
$query = "insert into datetable(when) values($1)";
/*     vvvvvvvvvvvvvvv              vvvvvvvvv^^ */
$res = pg_query_params($db, $query, [$mydate]);

http://php.net/manual/en/function.pg-escape-literal.php
http://php.net/manual/en/function.pg-escape-string.php
http://php.net/manual/en/function.pg-query-params.php