当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()时的完整错误是:
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
我的密码怎么了?
发布于 2018-02-28 08:07:13
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
或与演员:
postgres=# PREPARE p AS select concat(cast($1 as text));
PREPARE
我还没有用PDO进行测试,但假设它会工作(考虑到它如何处理参数以生成准备好的语句)来将查询更改为:
"...identification LIKE '%' || :identification || '::text%'..."
或者在查询中使用‘财政’操作符而不是concat
:
identification LIKE '%' || :identification || '%'
编辑:顺便说一下,如果您想要找到参数:X
是identification
的子字符串,则这个子句更安全:strpos(identification, :X) > 0
,因为:X
可能包含'%‘或'_’,而不会在匹配中造成任何副作用,这与LIKE
的情况相反。
https://stackoverflow.com/questions/49033241
复制