PHP:Postgresql查询中的变量

编程入门 行业动态 更新时间:2024-10-27 06:19:45
本文介绍了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查询中的变量

本文发布于:2023-10-13 20:47:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1489032.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   PHP   Postgresql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!