Is it possible to execute functions created in the PostgreSQL database engine through my PHP query?...
It is clear to me that the triggers are executed as soon as you make changes to the tables in your DB, however, I am still wondering if it is possible to do the following:
I have the sum() function created in the PostgreSQL engine
create or Replace function suma(num1 integer, num2 integer) returns integer
as
$$
select num1 + num2;
$$
Language SQL;
what I try to do is in my code editor and with PHP the following:
$num1 = (isset($_POST['num1'])) ? $_POST['num1']:"";
$num2 = (isset($_POST['num2'])) ? $_POST['num2']:"";
$suma = pg_query($conn,"SELECT suma($num1,$num2)"); <-- aqui llamo la función suma de postgresql
echo $suma;
before being able to enter the variables it is throwing me an error:
Warning: pg_query(): Query failed: ERROR: syntax error at or near "," LINE 1: SELECT sum(,) ^ in C:\xampp\htdocs\moca\sections\image.php on line 49
There are several things in your code:
You can simplify data collection by using the null merge operator (PHP >7) or a ternary operator (PHP <7)
Since you have indicated that the two parameters are of type
integer
in the function signature,(num1 integer, num2 integer)
you must force an integer conversion when you create the data that you will pass to the function. Even if you have indicated in a form a numeric type in theinput
, when PHP receives them it converts them to a typestring
, you can easily see that by doing avar_dump($_POST)
.Since, as the documentation says , it
pg_query()
returns a query result resource on success orfalse
on error, you can't treat the result of the call as if it were a string, with oneecho
or the other, but use the methods of that arranges that controller to read the data . For the case at hand, we will use 1pg_fetch_row()
to read the data .Incidentally, the same documentation discourages the use of
pg_query()
when handling external parameters , because they pose a serious security risk in the form of SQL injection 2 . It is better to usepg_query_params()
, and we will do that.So it should work like this:
Grades:
pg_fetch_
.