本文介绍了PHP:Postgresql查询中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这两个变量
$number = 1;
$word = "one";
,我想在pg_query中使用它们。
and I want to use them in a pg_query.
这就是我得到的:
$result = pg_query($con, 'UPDATE a SET z = ARRAY[{$number}] WHERE word = {pg_escape_literal($word)}');
但这不起作用。
推荐答案
要使用字符串插值,必须使用双引号:
To use string interpolation, you have to use double quotes:
$x = 3;
"This works: $x" // This works: 3
'This does not: $x'; // This does not: $x
您也无法将函数调用插入到像'重新尝试使用 {pg_escape_literal($ word)}
。您需要先对变量进行转义,然后才能将其插值到字符串中:
You also can't interpolate function calls into strings like you're attempting with {pg_escape_literal($word)}
. You'll need to escape the variable before interpolating it into the string:
$word_esc = pg_escape_literal($word);
$result = pg_query(
$con,
"UPDATE a SET z = ARRAY[$number] WHERE word = $word_esc"
);
您也可以使用 sprintf
:
$result = pg_query(
$con,
sprintf(
"update a set z=ARRAY[%d] where word = %s",
$number,
pg_escape_literal($word)
)
);
但是最好最安全的方法是使用 pg_query_params
函数,因为您不会转义任何参数。并且很容易忘记并使您的站点遭受SQL注入攻击。
But the best and safest is to use pg_query_params
function, as you don't escape any parameter. And it is very easy to forget and expose your site to SQL-injection attacks.
$result = pg_query_params(
'update a set z=ARRAY[$1] where word = $2',
array($number,$word)
)
这篇关于PHP:Postgresql查询中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!