使用PDO在两个不同的表中显示数据

时间:2018-08-13 15:46:25

标签: php pdo

表名:-主题。
主键:-sid

*------------------*    
| sid    | sname   |    
*------------------*    
| 1      | C++     |    
| 2      | PHP     |    
| 3      | Java    |    
*------------------*

表格名称:-问题

主键:-qid
  外键:-sid

*--------------------------------------------------------------------------*    
| qid | sid | question     | ans_one    | ans_two    |  correct_ans        |    
*--------------------------------------------------------------------------*    
| 1   |  2  | question 1   | answer one | answer two |  correct answer one |    
| 2   |  3  | question 2   | answer one | answer two |  correct answer two |    
| 3   |  2  | question 3   | answer one | answer two |  correct answer two |    
| 4   |  1  | question 4   | answer one | answer two |  correct answer one |    
| 5   |  2  | question 5   | answer one | answer two |  correct answer one |    
*--------------------------------------------------------------------------*

这是数据库中的两个表。我将使用PDO显示问题表中的所有数据。我进行了编码,以从查询表中获取所有数据。

    $result = db::$connection->prepare('SELECT `qid`,`sid`,`question`,`ans_one`,`ans_two`,`ans_three`,`ans_four`,`correct_ans`
                        FROM `question`
                        ORDER BY `qid` ASC');
       $result->execute();
       $result->fetchAll();

问题是,我需要在视图表中显示主题名称。现在显示主题ID。 我怎样才能做到这一点?

输出必须是这样的:-

*-------------------------------------------------------------------------------*    
| #   | Subject | Question     | Answer_One    | Answer_One    |  Correct_Ans  |    
*-------------------------------------------------------------------------------*    
| 1   |  PHP    | question 1   | answer one    | answer two    |  correct answer one |    
| 2   |  Java   | question 2   | answer one    | answer two    |  correct answer two |    
| 3   |  C++    | question 3   | answer one    | answer two    |  correct answer two |            
*--------------------------------------------------------------------------------*

1 个答案:

答案 0 :(得分:1)

您需要使用JOIN来获取主题名称,而不是ID(sid):

SELECT qid, subject.sname AS sname, question, ans_one, ans_two, correct_ans 
FROM question LEFT JOIN subject ON question.sid = subject.sid
ORDER BY qid ASC
  

演示: https://www.db-fiddle.com/f/key8M32fKAEugHKo6KMAus/0

因此您可以使用以下PHP代码:

$result = db::$connection->prepare('SELECT qid, subject.sname AS sname, question, ans_one, ans_two, correct_ans 
    FROM question LEFT JOIN subject ON question.sid = subject.sid
    ORDER BY `qid` ASC');
$result->execute();
$result->fetchAll();