I have a function which selects a list of records from a table of feedback forms. At the moment the query is based on both a course ID and user ID:
$sql = "SELECT * FROM `feedback` WHERE course_id = :course_id AND user_id = :user_id LIMIT 1";
$stmt = $this->ci->db->prepare($sql);
$result = $stmt->execute([
"course_id" => $course_id,
"user_id" => $user_id
]);
$results = $stmt->fetch(PDO::FETCH_ASSOC);
I want to make this so the user ID is optional but not sure how to write that most efficiently?
For example, I could do something like this:
if ($user_id) {
$sql = "SELECT * FROM `feedback` WHERE course_id = :course_id AND user_id = :user_id LIMIT 1";
$stmt = $this->ci->db->prepare($sql);
$result = $stmt->execute([
"course_id" => $course_id,
"user_id" => $user_id
]);
} else {
$sql = "SELECT * FROM `feedback` WHERE course_id = :course_id LIMIT 1";
$stmt = $this->ci->db->prepare($sql);
$result = $stmt->execute([
"course_id" => $course_id,
]);
}
$results = $stmt->fetch(PDO::FETCH_ASSOC);
But that seems very inefficient. The trouble is that if I omit "user_id" => $user_id
(in the first block of code) then my $sql
is invalid because the number of bound parameters won't match.
What's the best way around this?