1

I am trying to execute a query that joins several tables using the same foreign key via the below query but it returns false.

$question_id = 11406;

$query = $db->prepare("SELECT q.question_attempts_permitted, q.question_range, a.answer_text, r.attempt_count 
                           FROM checkup_questions q, checkup_answers a, user_responses r 
                           WHERE a.question_id=:question_id AND q.question_id=:question_id AND r.question_id=:question_id");
$query->bindValue(':question_id', $question_id, PDO::PARAM_INT);
$query->execute();

However, if I inject the question_id directly the query returns the desired result.

$query = $db->prepare("SELECT q.question_attempts_permitted, q.question_range, a.answer_text, r.attempt_count 
                       FROM checkup_questions q, checkup_answers a, user_responses r 
                       WHERE a.question_id=11406 AND q.question_id=11406 AND r.question_id=11406");
$query->execute();

Is there some limitation with the bindValue interface that causes the first query to fail while the second one returns as expected?

user1392897
  • 831
  • 2
  • 9
  • 25

1 Answers1

3

Query text should be rewritten using JOIN:

$query = $db->prepare("
    SELECT q.question_attempts_permitted, q.question_range, a.answer_text, r.attempt_count 
    FROM checkup_questions q 
    JOIN checkup_answers a ON a.question_id = q.question_id
    JOIN user_responses r ON r.question_id = q.question_id
    WHERE q.question_id=:question_id
");
// you can provide placeholder without `:`
$query->bindValue('question_id', $question_id, PDO::PARAM_INT);
$query->execute();

Here you have only one placeholder.

u_mulder
  • 54,101
  • 5
  • 48
  • 64