Data coming from the client always needs to be validated and sanitized on the server side.
I.e. if $searchColumn
, $userColumn
, $tablename
, $table_id
and $user_id
come in as request variables, you need to check each of them for validity. Especially $userColumn
, $tablename
and $searchColumn
need to be checked carefully for SQL injections, because they are added before you call prepare()
.
If you don't require the flexibility, you should enter the table and column names into the string.
You may even keep the user ID on the server side (as session variable) and only set it once on login, so you can get rid of the check completely. The tables referencing the user data still need to have a column with the user ID, though.
To ensure that a user can only access the data (s)he's supposed to see, you need to include the user ID in the query.
Example:
Imagine you have orders and order items in an 1 to m relation. You show the user the list of orders (s)he has made. When the user now chooses an order to display its items you can include the user ID in the query to ensure the user cannot access orders of other users.
Then the SELECT statement may look like this:
SELECT oi.name,
oi.description
oi.price
FROM order_item oi
INNER JOIN order o ON o.id = oi.order_id
WHERE o.id = ?
AND o.userID = ?
When the user then provides an ID of another user's order, there won't be any items returned.
This could also be done in two steps by first making a query against the order
table to check whether the order is assigned to the user and if so, making a query against the order items.