【问题标题】:Display data in a two different tables using PDO [duplicate]使用 PDO 在两个不同的表中显示数据 [重复]
【发布时间】:2019-01-20 09:46:45
【问题描述】:

表名称:- 主题。
主键:- 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 |            
*--------------------------------------------------------------------------------*

【问题讨论】:

标签: php pdo


【解决方案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();

【讨论】:

    猜你喜欢
    • 2017-07-04
    • 2017-01-06
    • 2022-10-12
    • 2017-12-22
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多