简体   繁体   English

获取打印表中的外键值

[英]Get foreign key value in printed table

I would like to print out my foreign keys from another table when I get the results from my query and print it in a table. 当我从查询中获得结果并将其打印在一个表中时,我想从另一个表中打印出我的外键。

My connect and query code: 我的连接和查询代码:

        $host="localhost";
        $username="****";
        $password="****";
        mysql_connect("$host", "$username", "$password")or die("cannot connect");
        mysql_select_db('****')or DIE(mysql_error());
        $tbl_name="ticket";

        $sql = "SELECT `id`, `subject`, `assigned`, `status`, `created`, `priority_id` FROM $tbl_name";
        $result = mysql_query($sql);

This is the code for printing out the results in a table 这是用于在表格中打印结果的代码

        $row = mysql_fetch_assoc($result);  
        print ('<table id="myTable" class="tablesorter" cellpadding="0" cellspacing="0">');
        print ("<thead>");
        print ("<th>ID</th>");
        print ("<th>SUBJECT</th>");
        print ("<th>ASSIGNED</th>");
        print ("<th>STATUS</th>");
        print ("<th>CREATED</th>");
        print ("<th>PRIORITY</th>");
        print ("</tr> </thead>");
        print ("<tbody>");
        while ($row) {
            $id = $row['id'];

            print ('<tr>'); 
            foreach ($row as $col => $value) {
                print ("<td data-href=tickets/edit.php?id=$id>$value</td>");
            }
            print ("</tr>");

            //Fetch next row    
            $row = mysql_fetch_assoc($result);
        }
        print ("</tbody>");
        print ("</table>"); 

        mysql_free_result($result);

So the priority ID in the ticket table is a foreign key to a "priority" table where I have three different rows 因此,票证表中的优先级ID是“优先级”表的外键,其中有三行

id     name
 1     low
 2     medium
 3     high

And the same for the assigned ID in the ticket table. 与票证表中分配的ID相同。 This is a name of a person which the ticket is assigned to. 这是票证分配给的人的名字。 It is stored in a "members" table 它存储在“成员”表中

id     name
 1     John
 2     Ben
 3     Brad

How would I go about this? 我将如何处理? I tried inner join, but with no luck. 我尝试了内部联接,但是没有运气。

(Also I know I should use mysqli, but had some issues with it. This worked, so I might change it later.) (我也知道我应该使用mysqli,但是它有一些问题。这可行,所以以后可以更改它。)

Try following: 请尝试以下操作:

$sql = "SELECT t.id, t.subject, m.name AS memberName, t.status, t.created, p.name AS priorityName 
        FROM $tbl_name AS t
        LEFT JOIN priority AS p ON t.priority_id = p.id
        LEFT JOIN members AS m ON t.assigned = m.id";

Edited: I forgot the ON in the second LEFT JOIN. 编辑:我在第二个LEFT JOIN中忘记了ON。 I just added. 我刚刚补充。

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

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