Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode an array as URL parameter, extract in in PHP and pass to Postgres as function parameter

If I have a correctly working postgres function (similar to below);

package."func_SetValues"(id integer, values integer[])
    DECLARE
        i integer;
    BEGIN
    FOR i IN 1..array_upper(values, 1) 
      LOOP
       EXECUTE package."func_DoStuff"(id, values[i]);
      END LOOP;
    END
    LANGUAGE 'plpgsql' VOLATILE

And, a PHP script, doStuff.php, calling this function which accepts and uses the values as url encoded parameters.

$dbconn = pg_connect("host=192.168.1.222 port=5432 dbname=betya user=betya_user password=bettyboo")
    or die('Could not connect: ' . pg_last_error());
$query = 'SELECT * FROM package."func_SetValues"($1, $2)';
$result=pg_prepare($dbconn, "qy", $query);
$paramater1=$_REQUEST['id'];    
$paramater2=$_REQUEST['arr']; 
$result=pg_execute($dbconn, "qy", array($paramater1, $paramater2));

while($e=pg_fetch_assoc($result))
$output[]=$e;

print(json_encode($output));
pg_free_result($result);
pg_close($dbconn);

To test the PHP script, does the following URL correctly encode the array 'arr' in a way that PHP can "Request" the values and can pass to postgres in away that it understands? Or is further functionality required in the script to correctly pass to the pg_execute command?

http://192.168.1.50/server/doStuff.php?id=1790&arr[]=1788&arr[]=1790&arr[]=1805
like image 735
sMaN Avatar asked May 21 '26 20:05

sMaN


1 Answers

Yes, further code is required. The array has to be non-trivially converted to be passed as a parameter, because PG expects it in textual form as described in the doc: http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO

In another question: PHP array to postgres array , a PHP function to that effect has been already submitted to S.O., it might just be what you need (and ever better since it supports recursive arrays).

like image 200
Daniel Vérité Avatar answered May 23 '26 11:05

Daniel Vérité