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

问题描述 投票:1回答:1

我在CONCAT()WHERE时遇到问题PDO

代码:

<?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);

?>

当“识别”部分被评论时,代码有效。当我尝试使用CONCAT()时,它没有。

我尝试了CONCAT()的许多“版本”(并阅读了许多其他问题,比如这个:How do I create a PDO parameterized query with a LIKE statement?)但我总是指的是主要文档: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

我的代码出了什么问题?

postgresql pdo concat
1个回答
2
投票

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

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

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

解析器无法找出$1的数据类型,所以它在谨慎方面是错误的。

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

postgres=# PREPARE p AS select concat($1::text);
PREPARE

或与CAST运营商:

postgres=# PREPARE p AS select concat(cast($1 as text));
PREPARE

我没有使用PDO进行测试,但可能它会工作(给定它如何处理生成预准备语句的参数)以将查询更改为:

"...identification LIKE '%' || :identification || '::text%'..."

或使用'||'查询中的运算符而不是concat

identification LIKE '%' || :identification || '%'

编辑:BTW如果你想找到参数:Xidentification的子串,这个子句更安全:strpos(identification, :X) > 0,因为:X可能包含'%'或'_'而不会在匹配中造成任何副作用,这与发生在LIKE

© www.soinside.com 2019 - 2024. All rights reserved.