简体   繁体   English

如何获取PHP中外键引用的列名

[英]How do I get the column name of a foreign key reference in PHP

I have got two tables: category and quiz 我有两个表:类别和测验

In category I have : category_id | 类别中,我有:category_id | category_name | category_name |

In quiz I have : quiz_id | 测验中,我有:quiz_id | quiz_name | 测验名称| quiz_category_id| quiz_category_id | quiz_duration quiz_duration

As you can notice, quiz_category_id is a FOREIGN KEY reference. 您会注意到,quiz_category_id是FOREIGN KEY参考。

This is the code I have so far: 这是我到目前为止的代码:

<table>
   <thread>
      <tr>
         <th>quiz name</th>
         <th>quiz category</th>
         <th>quiz duration</th>
     </tr>
   </thread>
     <tbody>
        <?php foreach (get_all_exam() as $r) { ?>
         <tr>
             <td><?php echo $r['quiz_name'] ?></td>
             <td><?php echo $r['quiz_category_id'] ?></td> // I am getting the id value not the name
             <td><?php echo $r['quiz_duration'] ?></td>
        </tr>
        <?php } ?>
     </tbody>
</table>

get_all_exam() is a function and here it is: This is where I do the sql query get_all_exam()是一个函数,在这里是:这是我执行sql查询的地方

function get_all_exam () {
    $data = array();

    $result = mysql_query("SELECT * FROM `quiz`");

    while ($row = mysql_fetch_assoc($result)) {
        $data [] = $row;
    }

    return $data;
} 

So at the minute, it just prints out for example; 因此,此刻仅打印出来;例如

| | quiz name | 测验名称 | | | quiz category | 测验类别 | | | quiz duration | 测验时间 |

|practice ex | |练习前| |23| | 23 | |5 minutes| | 5分钟|

Instead of it saying 23 I want it so that it looks up on the corresponding table to get the name 而不是说23我想要它,以便它在相应的表上查找以获取名称

Thanks 谢谢

SELECT quiz.quiz_name, category.catagory_name, quiz.quiz_duration 
FROM quiz LEFT JOIN category 
ON (quiz.quiz_category_id = category.category_id)

Inside select statement, select what you want, you could also say SELECT quiz.*, category.* , but be careful if you have same field names, you might want to retrieve some with AS . 在select语句中,选择所需的内容,也可以说SELECT quiz.*, category.* ,但是要小心,如果您具有相同的字段名称,则可能希望使用AS进行检索。

LEFT JOIN means - always show from left table, even if there is no value in the right table; LEFT JOIN意思是-即使右表中没有值,也总是从左表中显示; thus, it will show quiz_id, even if there is no corresponding category_id. 因此,即使没有相应的category_id,它也会显示quiz_id。 RIGHT JOIN will do just the opposite. RIGHT JOINRIGHT JOIN相反的作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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