1

Let's say I have these two variables

$number = 1;
$word = "one";

and I want to use them in a pg_query.

This is what I've got:

$result = pg_query($con, 'UPDATE a SET z = ARRAY[{$number}] WHERE word = {pg_escape_literal($word)}');

But it doesn't work..

0

2 Answers 2

2

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

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

You could also use sprintf:

$result = pg_query(
  $con,
  sprintf(
    "update a set z=ARRAY[%d] where word = %s",
    $number,
    pg_escape_literal($word)
  )
);

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)
)
Sign up to request clarification or add additional context in comments.

2 Comments

Using pg_query_params instead of escaping would be better.
I've edited meagar's answer - removed quotes in examples, as pg_escape_literal will quote variable, improved layout of examples and added pg_query_params example as it is the best way.
0

Use double instead of single quotes: Double quoted strings expand variables into their values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.