SQLPage built-in functions

In addition to normal SQL functions supported by your database, SQLPage provides a few special functions to help you extract data from user requests.

These functions are special, because they are not executed inside your database, but by SQLPage itself before sending the query to your database. Thus, they require all the parameters to be known at the time the query is sent to your database. Function parameters cannot reference columns from the rest of your query. The only case when you can call a SQLPage function with a parameter that is not a constant is when it appears at the top level of a SELECT statement. For example, SELECT sqlpage.url_encode(url) FROM t is allowed because SQLPage can execute SELECT url FROM t and then apply the url_encode function to each value.

The sqlpage.variables function

Introduced in SQLPage 0.15.0.

Returns a JSON string containing all variables passed as URL parameters or posted through a form.

The database's json handling functions can then be used to process the data.

Example: a form with a variable number of fields

Making a form based on questions in a database table

We can create a form which has a field for each value in a given table like this:

select 'form' as component, 'handle_survey_answer.sql' as action;
select question_id as name, question_text as label from survey_questions;

Handling form responses using sqlpage.variables

In handle_survey_answer.sql, one can process the form results even if we don't know in advance how many fields it contains. The function to parse JSON data varies depending on the database engine you use.

In SQLite

In SQLite, one can use json_each :

insert into survey_answers(question_id, answer)
select "key", "value" from json_each(sqlpage.variables('post'))

In Postgres

Postgres has json_each_text :

INSERT INTO survey_answers (question_id, answer)
SELECT key AS question_id, value AS answer
FROM json_each_text(sqlpage.variables('post')::json);

In Microsoft SQL Server

INSERT INTO survey_answers
SELECT [key] AS question_id, [value] AS answer
FROM OPENJSON(sqlpage.variables('post'));

In MySQL

MySQL has JSON_TABLE, and JSON_KEYS which are a little bit less straightforward to use:

INSERT INTO survey_answers (question_id, answer)
SELECT
    question_id,
    json_unquote(
        json_extract(
            sqlpage.variables('post'),
            concat('$."', question_id, '"')
        )
    )
FROM json_table(
    json_keys(sqlpage.variables('post')),
    '$[*]' columns (question_id int path '$')
) as question_ids

Parameters

method

Optional. The HTTP request method (GET or POST). Must be a literal string. When not provided, all variables are returned.