note 115064 added to function.pg-query-params

From: Date: Tue, 20 May 2014 16:53:29 +0000
Subject: note 115064 added to function.pg-query-params
Groups: php.notes 
Request: Send a blank email to php-notes+get-199583@lists.php.net to get a copy of this message
Debugging parameterised queries can be tedious, if you want to paste the query directly into PSQL. Here is a trick that helps: <?php $sql = "SELECT * from table WHERE col_a = $1 and col_b=$2 and col_c=$3"; $params = array (42, "a string", NULL); $debug = preg_replace_callback( '/\$(\d+)\b/', function($match) use ($params) { $key=($match[1]-1); return ( is_null($params[$key])?'NULL':pg_escape_literal($params[$key]) ); }, $sql); echo "$debug"; //prints: SELECT * from table WHERE col_a = '42' and col_b='a string' and col_c=NULL ?> This works correctly, except in the (unusual) case where we have a literal $N; the regexp replaces it where it shouldn't. For example: <?php //Both ' ... $1 ... ' and $1 get replaced; the former is wrong, the latter is right. $sql = "SELECT 'Your bill is for $1' AS invoice WHERE 7 = $1"; $params = array(7); //$debug: SELECT 'Your bill is for $7' AS invoice WHERE 7 = '7'" ?> ---- Server IP: 72.52.91.14 Probable Submitter: 82.10.237.122 ---- Manual Page -- http://php.net/manual/en/function.pg-query-params.php Edit -- https://master.php.net/note/edit/115064 Del: integrated -- https://master.php.net/note/delete/115064/integrated Del: useless -- https://master.php.net/note/delete/115064/useless Del: bad code -- https://master.php.net/note/delete/115064/bad+code Del: spam -- https://master.php.net/note/delete/115064/spam Del: non-english -- https://master.php.net/note/delete/115064/non-english Del: in docs -- https://master.php.net/note/delete/115064/in+docs Del: other reasons-- https://master.php.net/note/delete/115064 Reject -- https://master.php.net/note/reject/115064 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#199583) next »