简体   繁体   中英

Unsuccessfully using JOINs to query MySQL database with PHP

Here is my database schema:

user
*user_id
*username
*password
*etc

quiz_response
*response_id
*user_id
*question_id
*response
*is_correct
*answer_time

question_choice
*choice_id
*question_id
*is_correct
*choice (VARCHAR)

question
*question_id
*quiz_id
*question (VARCHAR)

quiz
*quiz_id
*title (VARCHAR)

I am building a quiz web-app using PHP and I am having trouble. Currently, I am trying -- with no luck -- this query and I know where the problem is, I just don't know how to solve it. Hence, why I am here on SO

// Grab the response data from the database to generate the form
    $query = "SELECT qr.response_id AS r_id, qr.question_id, qr.response, q.question, quiz.title " . 
        "FROM quiz_response AS qr " . 
        "INNER JOIN question AS q USING (question_id) " . 
        "INNER JOIN quiz USING (quiz_id) " . 
        "WHERE qr.user_id = '" . $_SESSION['user_id'] . "'";
    $data = mysqli_query($dbc, $query) or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $query"); 

At this point I feel my second Inner Join (INNER JOIN quiz USING (quiz_id)) is the problem. When I don't include this line and remove the quiz.title from the query it works. So, my question is how do I maintain an atomic database schema while still grabbing the quiz title based on the quiz_id from the table 'question'? Any help would be much appreciated!

Try with:

// Grab the response data from the database to generate the form
    $query = "SELECT qr.response_id AS r_id, qr.question_id, qr.response, q.question, quiz.title " . 
        "FROM quiz_response qr " . 
        "INNER JOIN question q USING (question_id) " . 
        "INNER JOIN quiz ON quiz.quiz_id = q.quiz_id " . 
        "WHERE qr.user_id = '" . $_SESSION['user_id'] . "'";
    $data = mysqli_query($dbc, $query) or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $query"); 

I believe that the problem is that quiz_id is not in quiz_response. I use the ON keyword. Try:

// Grab the response data from the database to generate the form
$query = "SELECT qr.response_id AS r_id, qr.question_id, qr.response, q.question, 
          quiz.title " . 
         "FROM quiz_response AS qr " . 
         "INNER JOIN question AS q ON (q.question_id = qr.question_id) " . 
         "INNER JOIN quiz ON (quiz.quiz_id = q.quiz_id) " . 
         "WHERE qr.user_id = '" . $_SESSION['user_id'] . "'";
$data = mysqli_query($dbc, $query) or 
         die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $query");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM