pclib  3.0.0
Lightweight PHP framework
Dynamic SQL

Dynamic SQL is the proud name for SQL with parameters, which is supported by PClib database functions such as Db->query() or Grid->setQuery()

  • Parameters are included into SQL in curly brackets like this: {PARAMETER}.
  • Values of the parameters can be read from array or non-array function arguments.
  • Each parameter is escaped with Db->escape() before it is included into SQL.
//using associative array
$sql = "SELECT * FROM PERSONS WHERE PROFESSION='{PROFESSION}' AND MONEY>'{MONEY}'";
$db->query($sql, ['PROFESSION' => 'baker', 'MONEY' => 1000]);
//using indexed array (there are indexes to the array in square brackets)
$sql = "SELECT * FROM PERSONS WHERE PROFESSION='{0}' AND MONEY>'{1}'";
$db->query($sql, ['baker', 1000]);
//using plain function arguments
$sql = "SELECT * FROM PERSONS WHERE PROFESSION='{0}' AND MONEY>'{1}'";
$db->query($sql, 'baker', 1000);

If your parameter is numeric, you can prefix it with '#' and you will sure that only integer can be used as this parameter.
Example: MONEY='{#MONEY}'

If variable is array, it is converted into list of values suitable for IN clausule. Values in array are escaped.

$db->query("select * from A where X in ('{X}')", ['X' => [1,2]]);
Dynamic at least
Sometimes we need exclude some parts of SQL. For example we have search form and when user doesn't fill field MONEY or NAME, it means "this fields doesn't matter". We will want exclude conditions with empty parameters from query. For excluding line from query you can prefix it with tilda '~'. Note that everything what will be excluded, must be in one line.
$params = ['PROFESSION' => 'baker', 'MONEY' => 1000, 'DO_OREDER' => 1];
$db->query(
"SELECT * FROM PERSONS
WHERE 1
~ AND PROFESSION = '{PROFESSION}'
~ AND NAME like '{NAME}%'
~ AND MONEY > {#MONEY}
~ ORDER BY BIRTHDATE {?DO_ORDER}", $params
);
//Perform query
// SELECT * FROM PERSONS WHERE 1
// AND PROFESSION = 'baker' AND MONEY > 1000
// ORDER BY BIRTHDATE

Parameter NAME is empty, so line with NAME is excluded from the query. We have new parameter DO_ORDER here, prefixed with '?'. This is conditional parameter - his value is never included into query, but when it is empty, line is omitted. In search form can be (for example) checkbox "Order by birthdate".

Class Grid
In class Grid, parameters of sql in Grid->setQuery() are coming from array Grid->filter. For session grid - its fiter is stored in session. Example:
if ($searchform->submitted)
$mygrid->filter = $searchform->values;
$mygrid->setquery(
"SELECT * FROM PERSONS
WHERE 1
AND PROFESSION = '{PROFESSION}'
AND NAME like '{NAME}%'
AND MONEY > {MONEY}
ORDER BY BIRTHDATE"
);

/*!