简体   繁体   中英

Escape a literal so that it is wrapped with double quotes

We use doctrine 2 and want to write parameterised code like this:

attributes @> \'{' . $con->quote($attrId) . ':' . (int)$value . '}\'';

to have a query like this:

WHERE attributes @>'{"color":14}';

The "color" is the custom (user chosen) name of an attribute. So I feel that quote() is an appropriate function to shield it. But it wraps a parameter with single quotes, what makes the request syntax incorrect.

quoteIdentifier() function wraps with double quotes, BUT I'm not sure if it's right to use it in this context.

How to build a safe code to get the request I need?

Here is a way to do it with json_build_object and pg_exec_params :

<?php
$dbconn = pg_connect('');
$data = 'some"th\'ing';
pg_query_params($dbconn, 'SELECT json_build_object($1::text, $2::integer)', [$data, 14]);
?>

You need the explicit type casts so that PostgreSQL knows whether the argument is a string or a number.

You can include the double quotes in the string.

$attr = '{"' . $attrId . '":' . (int) $value . '}';

Don't depend on quoting to keep you safe, but instead execute the query with a method that binds the value to a prepared statement.

$statement = $con->executeQuery('SELECT * FROM your_table WHERE attributes @> ?', [$attr]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM