问题
I'm trying to convert this query from a normal pg_query()
to pg_prepare() & pg_execute()
. Its a generic query that I reuse when I need to update different tables from different pages in order to keep my code clean.
I've just realised that parameters can be used only in where
clauses and not in other parts of the query.
$res = pg_query($con, "update " . $_REQUEST['table'] . " set " . $_REQUEST['colname'] . "=" . $colval . " where " . $_REQUEST['colnameid'] . "=" . $_REQUEST['colvalid'] . " returning " . $_REQUEST['colnameid'] );
Tried this code:
$res = pg_prepare($con, "upd", "update $1 set $2=$3 where $4=$5 returning $6");
$res = pg_execute($con, "upd", array($_REQUEST['table'],$_REQUEST['colname'],$colval,$_REQUEST['colnameid'],$_REQUEST['colvalid'],$_REQUEST['colnameid'] ));
This is failing. Is there any way to achieve this or a better approach to this problem?
回答1:
No, you cannot bind identifiers, only values.
Identifiers (table names, field names, etc.) are not supposed to be user inputs in the first place. It is a very bad idea to handle them in such a way.
来源:https://stackoverflow.com/questions/36786502/php-pg-prepare-table-name-as-parameter