Postgresql SQLSTATE[42P18]:不确定数据类型与 PDO 和 CONCAT

Nih*_*vel 4 postgresql pdo concat

我在, inCONCAT()上使用时遇到问题。WHEREPDO

编码:

<?php
require_once('config.php');

$fdate = '01/01/2010';
$tdate = '31/12/2030';
$identification = '';

$count = "SELECT count(*) as total FROM ( select time_id from doc_sent WHERE date >= :fdate AND date <= :tdate AND identification LIKE concat('%',:identification,'%') ) x;";

//$count = "SELECT count(*) as total FROM ( select time_id from doc_sent WHERE date >= :fdate AND date <= :tdate ) x;";


$stmt_count_row_main_table = $pdo->prepare($count);
$stmt_count_row_main_table->execute(['fdate' => $fdate, 'tdate' => $tdate, 'identification' => $identification]);
//$stmt_count_row_main_table->execute(['fdate' => $fdate, 'tdate' => $tdate]);
$count_row_main_table = $stmt_count_row_main_table->fetch();

print_r( $count_row_main_table);

?>
Run Code Online (Sandbox Code Playgroud)

该代码在“标识”部分被注释时起作用。当我尝试使用 CONCAT() 时,它没有。

我尝试了 CONCAT() 的许多“版本”(并阅读了许多其他问题,例如:如何使用 LIKE 语句创建 PDO 参数化查询?)但我总是参考主要文档: https://www .postgresql.org/docs/9.1/static/functions-string.html

其中说:

concat('abcde', 2, NULL, 22) --> abcde222

使用 CONCAT() 时的 FULL 错误是:

PHP Fatal error:  Uncaught PDOException: SQLSTATE[42P18]: Indeterminate datatype: 7 ERROR:  could not determine data type of parameter $3 in /var/www/pdo-reporter/show.php:17\nStack trace:\n#0 /var/www/pdo-reporter/show.php(17): PDOStatement->execute(Array)\n#1 {main}\n  thrown in /var/www/pdo-reporter/show.php on line 17
Run Code Online (Sandbox Code Playgroud)

我的代码有什么问题?

Dan*_*ité 5

CONCAT 是一个接受 VARIADIC 参数列表的函数,这意味着 postgres 内部会将它们转换为相同类型的数组。

postgres=# \df concat
                          List of functions
   Schema   |  Name  | Result data type | Argument data types | Type 
------------+--------+------------------+---------------------+------
 pg_catalog | concat | text             | VARIADIC "any"      | func
Run Code Online (Sandbox Code Playgroud)

尝试将输入类型解析为单一类型时,SQL 解析器失败。它可以以这种更简单的形式重现:

postgres=# PREPARE p AS select concat('A', $1);
ERROR:  could not determine data type of parameter $1
Run Code Online (Sandbox Code Playgroud)

解析器无法弄清楚的数据类型,$1因此它在谨慎方面出错。

一种简单的解决方案是将参数转换为文本:

postgres=# PREPARE p AS select concat($1::text);
PREPARE
Run Code Online (Sandbox Code Playgroud)

或使用 CAST 运算符:

postgres=# PREPARE p AS select concat(cast($1 as text));
PREPARE
Run Code Online (Sandbox Code Playgroud)

我还没有用 PDO 测试过,但大概它会起作用(考虑到它如何处理参数以生成准备好的语句)将查询更改为:

"...identification LIKE '%' || :identification || '::text%'..."
Run Code Online (Sandbox Code Playgroud)

或使用“||” 运算符而不是concat在查询中:

identification LIKE '%' || :identification || '%'
Run Code Online (Sandbox Code Playgroud)

编辑:顺便说一句,如果您想找到一个参数:X是 的子字符串identification,则此子句更安全:strpos(identification, :X) > 0,因为:X可能包含 '%' 或 '_' 而不会在匹配中造成任何副作用,这与LIKE.