My code pulls the details of a report, but I only want the details displayed if that particular report is associated to the user attempting to view it. I'm wondering if it's more efficient/proper to add a second WHERE
clause to the query or if I should just use PHP to check the associated user id? I would prefer the latter since it would be easier to give the administrators access to all records.
<?php
$query = mysql_query("SELECT report_id, report_user, report_text
FROM reports
WHERE report_id = '$rid'
AND report_user = '$uid'");
$report = mysql_fetch_assoc($query);
?>
OR
<?php
$query = mysql_query("SELECT report_id, report_user, report_text
FROM reports
WHERE report_id = '$rid'");
$report = mysql_fetch_assoc($query);
if ($report['user'] !== $uid) {
// Access Denied
}
?>
Thanks in advance! Billy
I would argue that you should go with filtering inside the query option. It is more efficient and would protect user privacy better in case you have some bugs in your php code. Regarding the admin ability to view reports, you can craft the query dynamically.
$sql = "SELECT report_id, report_user, report_text
FROM reports
WHERE report_id = ?";
if($userContext)
{
$sql .= " AND report_user = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('dd', $rid, $uid);
}
else //admin context
{
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('d', $rid);
}
What ever you do make sure to bind you variables.
The best way would be to make the first query dynamic, in regards to if an admin is logged in or not. Something like this:
query = ".."
if (user != admin)
query .= " AND report_user = " . intval(user_id)
Assuming that your table is properly indexed, the difference in performance is minimal. One could argue that the SQL approach is less error prone as it does not depend on your PHP logic. On the other hand, it is easier to give users a meaningful error message if you use the second approach, because it is then possible to determine exactly why there is no report to display. In the first approach, you do not know whether the report does not exist or if the user is just not allowed to view it. I would, however, go for the first one.
Also, you should consider using PDO. Perhaps you just used the technique you did for the sake of the example, but just saying.