A safe subset might be so small it’s not usable, but still, would allowing only a certain character set be safe? What about white-listing certain tokens in the stream?
Example:
// Calculation for a SELECT column, input from user
$src = 'ROUND((1 - (purchase_price / selling_price)) * 100, 2)';
// Split into tokens
$tokens = token_get_all('<?php ' . $src);
// Validate all tokens by white-list, alphanumeric, or similar
The full query is constructed on server-side, including WHERE, FROM, LIMIT, etc.
2
For the most part, the only safe and readily available option would be to use a prepared statement. In a prepared statement, you can expose your SQL query via wildcards. For example, consider this query:
SELECT *
FROM yourTable
WHERE purchase_price > ?;
To the ?
placeholder you could bind some minimum purchase value coming from outside the database.
However, note that database objects (database, table, column names, etc.) cannot be represented by a ?
placeholder. Doing so would be a large security risk, as a malicious user could attempt to read from a table to which it should not have access.